Angular 1.5“track by”ruines binding in ng-options

时间:2017-01-16 12:42:24

标签: javascript angularjs

我需要从ajax加载的数据中选择组合框中的选项。该数据作为对象列表出现。问题是ng-option通过引用比较对象,因此将模型设置为对象元素会导致在组合框中出现新的空选项,而不是选择正确的选项。

已知的解决方法是使用track by表达式。 以下是示例代码:

var myApp = angular.module("myApp", []);

myApp.controller("myCtrl", function($scope) {

  $scope.roles =[
    { key:"administrator", value:"ROLE_ADMIN" },
    { key:"operator", value:"ROLE_OPERATOR" }, 
  ];

  // this emulates data from server
  // won't work without 'track by'
  $scope.role={ key:"administrator", value:"ROLE_ADMIN" };

});

模板:

<body ng-app="myApp" ng-controller="myCtrl">
0: <input ng-model="roles[0].key" />
<br>
1: <input ng-model="roles[1].key" />

<br>
  select role: <select ng-model="role" ng-options="r.key for r in roles track by r.value">
  </select>

  <pre>selected role={{role|json}}</pre>
</body>

这里出现了另一个问题。当一个人在组合框中选择角色然后 更改文本框中的“键”属性,然后选定的角色保持不变。所以看起来绑定突然被打破了。

https://jsfiddle.net/xLqackxw/8/

1 个答案:

答案 0 :(得分:0)

来自Angular文档https://docs.angularjs.org/api/ng/directive/ngOptions

<select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>

所以:

<select ng-model="role" ng-options="r as r.key for r in roles track by r.value"></select>

&#39; $ scope.role&#39;值将是{key:&#34; administrator&#34;,value:&#34; ROLE_ADMIN&#34; }或{key:&#34; operator&#34;,value:&#34; ROLE_OPERATOR&#34; }