Angularjs select不会将匹配模型标记为已选中

时间:2014-09-07 01:28:09

标签: javascript angularjs angularjs-ng-options angularjs-ng-model

我的ngModel在选择未显示为已选中时出现问题。 id和name都匹配但不起作用,请参阅selectedState。将模型指向options数组中的实际对象,请参阅selelectedState2。不知道发生了什么......

小提琴: http://jsfiddle.net/fedorsmirnoff/b49n4Ldp/2/

<select ng-model="selectedState" ng-options="state.name for state in stateOptions"></select>

<select ng-model="selectedState2" ng-options="state.name for state in stateOptions"></select>

function MainCtrl($scope) {
 $scope.stateOptions = [
     {id: 1, name: "Alaska"},
     {id: 2, name: "Montana"},
     {id: 3, name: "Nebraska"},
     {id: 4, name: "Texas"}
  ]

 $scope.selectedState = {id: 2, name: "Montana"};

 $scope.selectedState2 = $scope.stateOptions[1];

}

6 个答案:

答案 0 :(得分:31)

这是因为每个对象都有Angular提供的$hashKey,Angular使用它来确定它们是否相同。您正在$hashKey上创建一个新对象(具有不同的$scope.selectedState)。您在$scope.selectedState2上设置的方式是正确的。

您还可以使用track bystate.id而不是对象的$hashKey制作Angular曲目:

<select ng-model="selectedState" ng-options="state.name for state in stateOptions track by state.id"></select>

答案 1 :(得分:8)

如果您提供的对象作为不包含对现有列表的引用的模型,则使用track by和模型的唯一值,以便不使用自定义唯一$$ hashKey, ng-options将使用您在轨道中提供的属性来跟踪正在设置的ng模型。

  ng-options="state.name for state in stateOptions track by state.id"

<强> Demo

不仅可以将ng-model设置为任何参考,而且它还具有很高的性能效果,特别是当您的列表被刷新时,元素将不会被删除和重新创建,而是仅仅角度将更新现有元素。

这是very good example for this

答案 2 :(得分:3)

Angular团队在ngSelect here的文档中说明了这个问题:

  

注意: ngModel按引用进行比较,而不是值。绑定到对象数组时这很重要。请参阅此jsfiddle中的示例。

 $scope.options = [
    { label: 'one', value: 1 },
    { label: 'two', value: 2 }
  ];

  // Although this object has the same properties as the one in $scope.options,
  // Angular considers them different because it compares based on reference
  $scope.incorrectlySelected = { label: 'two', value: 2 };

  // Here we are referencing the same object, so Angular inits the select box correctly
  $scope.correctlySelected = $scope.options[1];

答案 3 :(得分:2)

设置$ scope.selectedState时,实际上是在创建一个新的javascript对象,它不是$ scope.stateOptions的元素。因此,select元素不会从$ scope.stateOptions中选择相应的元素。

您可以使用&#39;跟踪&#39;在select表达式中,如果需要按唯一的attr值选择项目。

答案 4 :(得分:1)

尝试添加 在ng-options语句末尾按state.id进行跟踪。

答案 5 :(得分:0)

我认为Angular使用引用检查而不是比较具有相同属性的两个对象。在您的情况下,$ scope.selectedState2返回一个不同的对象。我通常使用understore从数组中查找所选项目以进行初始化。