NgSelect未在选择中选择选项

时间:2018-09-04 12:16:11

标签: javascript angular select dropdown angular-ngselect

Ng-Selected不能选择正确的选项,即使比较正确。我可以在输出中看到比较工作正常。

我的实际问题是,即使比较成功之后(不同于其他问题,Int和字符串比较返回false)。为什么不选择该选项。

我不能将option用于其他目的。其次,在复制到代码段时有一些错误。这就是为什么它不起作用。

var app = angular.module("app", []);
app.controller("HelloController", function($scope) {

  $scope.data = {
    ExpertiseId: null,
    userExperties = [{
      id: 1,
      ExpertyTitle: "Human Resource"
    }, {
      id: 2,
      ExpertyTitle: "Account & Finance"
    }, {
      id: 3,
      ExpertyTitle: "Information Technology"
    }, {
      id: 4,
      ExpertyTitle: "Business Management"
    }];
  }
});
<!DOCTYPE html>
<html lang="en">

<head>
  <title>AngularJS</title>

</head>

<body ng-app="app">
  <select name="ChooseExpertise" id="ChooseExpertise" class="form-control" ng-model="newAdmin.ExpertiseId" required>
    <option style="display:none" value="">CHOOSE_EXPERTISE</option> 
    <option ng-selected="{{option.id.toString() == data.ExpertiseId.toString()}}" value="{{option.id.toString()}}" ng-repeat="option in data.userExperties">{{option.id.toString()==data.ExpertiseId.toString()}}---{{option.ExpertyTitle}}</option>
  </select>
</body>

</html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

谢谢:)请帮助

1 个答案:

答案 0 :(得分:1)

您的代码中有几个错误。

  1. 对象表示法错误
  2. 您在任何地方都不能使用ng-controller
  3. 将脚本文件放置在html标签之外。
  4. ng选择的语法也是错误的

我已更正它们并更新了代码段。

var app = angular.module("app", []);
app.controller("HelloController", function($scope) {

  $scope.data = {
    ExpertiseId: 2,
    userExperties : [{
      id: 1,
      ExpertyTitle: "Human Resource"
    }, {
      id: 2,
      ExpertyTitle: "Account & Finance"
    }, {
      id: 3,
      ExpertyTitle: "Information Technology"
    }, {
      id: 4,
      ExpertyTitle: "Business Management"
    }]
  }
});
<!DOCTYPE html>
<html lang="en">

<head>
  <title>AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular.min.js"></script>
</head>

<body ng-app="app" >
<div ng-controller="HelloController">
  <select name="ChooseExpertise" id="ChooseExpertise" class="form-control" ng-model="newAdmin.ExpertiseId" required>
    <option  ng-selected="option.id === data.ExpertiseId" ng-repeat="option in data.userExperties" value="{{option.id}}">{{option.id}}</option>
  </select>
  </div>
</body>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</html>