ngOptions "track by" expression

thebringking picture thebringking · Apr 30, 2014 · Viewed 37.5k times · Source

I am trying to use the 'track by' expression to track selections by id, in an array of objects. However, I can't seem to make it work like I think it works.

//ids from server
$scope.serverDTO = ['1','2','3'];

//composed objects from the ID set
$scope.composedData = [{id:1,name:"test"},{id:2,name:"test"},{id:3,name:"test"}];

<!-- select box -->
<select ng-model="serverDTO" ng-options="item as item.name for item in composedData track by item.id"></select>

So based on the documentation I though that the options directive on load would see that the serverDTO has the 'track by' ids of 1, 2, and 3, and have those pre-selected. After the user modifies the selection I would need to do something like this to return the array to the server-

//recreate proper DTO [1,2,3];
$scope.serverDTO = $scope.serverDTO.map(function(val){
  return val.id;
});

Am I way off on how this is supposed to work?

Answer

jraede picture jraede · Apr 30, 2014

track by just helps Angular internally with array sorting as far as I know. The value of the options is defined by the first argument (in your case item). If you want it to be by id then you should use item.id as item.name for item in items