Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngOptions "track by" expression

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?

like image 682
thebringking Avatar asked Apr 30 '14 20:04

thebringking


People also ask

How does ng-options work as?

Definition and Usage. The ng-options directive fills a <select> element with <options>. The ng-options directive uses an array to fill the dropdown list. In many cases it would be easier to use the ng-repeat directive, but you have more flexibility when using the ng-options directive.

What is ngOptions?

The ngOptions attribute can be used to dynamically generate a list of <option> elements for the <select> element using the array or object obtained by evaluating the ngOptions comprehension expression.

How do I filter with Ng-options?

In AngularJS when you are using ng-options, you can filter out the options by calling a custom function you have in the controller. Let's say you have following set of employees and when you display all these employees inside HTML select using ng-options, you can see all the employees in a dropdown.

Why do we use track by?

If you are using "track by" then it will avoid generating DOM elements every times for element that are already rendered. It improves the rendering performance.


2 Answers

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

like image 190
jraede Avatar answered Oct 02 '22 05:10

jraede


"track by" is usefull when in ng-options array of objects and model you use object also. but you do not want track options by the reference of the object in model. Using "track by" you point that you track options by desired field of model.

in your case with "track by" $scope.serverDTO must be like {id:1,name:"test"}

like image 43
Vasiliy Mazhekin Avatar answered Oct 02 '22 03:10

Vasiliy Mazhekin