我有一个使用 ng-options 显示的对象数组,并使用 id 设置 ng-model。如果我在其上添加track by
,则无法选择该项目,如果不添加,则工作正常,为什么?代码如下:
angular.module('myApp', [])
.controller('MyController', ['$scope', function ($scope) {
$scope.countryList = [{id: 1, name: 'China'}, {id: 2, name: 'America'}, {id: 3, name: 'England'}]
$scope.country = 1;
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script>
<div class="container" ng-app="myApp">
<div ng-controller="MyController">
<p><select ng-model="country" ng-options="country.id as country.name for country in countryList"></select> no track by</p>
<p><select ng-model="country" ng-options="country.id as country.name for country in countryList track by country.id"></select> have track by, can't selected by id</p>
</div>
</div>
最佳答案
如上所述in this github issue - "ng-options track by and select as are not compatible"和 shown in this fiddle
“你不能将值作为集合标签与跟踪依据结合起来。你必须选择其中之一。”。
对于您的情况,选择应该是:
<select ng-model="country" ng-options="country as country.name for country in countryList track by country.id"></select>
在 JS 中
$scope.country = $scope.countryList[0];
选择的值将是对象,而不仅仅是 ID。
重点是,您必须在选择作为标签或按大小写轨道之间进行选择。
关于angularjs - 为什么无法通过 id 选择 'track by' 的 Angular ng-options,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40281793/