huguangju huguangju - 28 days ago 10
AngularJS Question

Why Angular ng-options with 'track by' can't selected by id

I have a array of objects that I'm displaying using ng-options, and set ng-model with id. If i add

track by
on it, the item can't selected, if not add, it working normal, why? The following code:



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>




Answer

As explained in this github issue - "ng-options track by and select as are not compatible" and shown in this fiddle

"you just can't combine value as label for collection with track by. You have to pick the one or the other.".

For your case, the select should be:

<select ng-model="country" ng-options="country as country.name for country in countryList track by country.id"></select>

and in JS

$scope.country = $scope.countryList[0];

JSFiddle here for your case.

The value selected will be the object and not just the id alone.

Again the point is, you have to chose between select as label or the track by case.