ngOptions track by to select the matched value from options

Happy Friday!

After AngularJS 1.2, you don’t need to use ng-repeat to display options for <select> element. Instead, it is recommended to use ng-options, such as this below,  where items is an Array of object item.

<select ng-model=”selectedItem” ng-options=”item as item.label for item in items”></select>

However, the above doesn’t display the selectedItem as selected if there is a match with the value of the object in the Array items.

 

No worries! AngularJS now has a nice expression to make that so easy to achieve, by using track by:

<select ng-model=”selectedItem” ng-options=”item as item.label for item in items track by item.value“></select>

Now if there is a match of values between the selectedItem and one Option in the Array, that Option is selected!

AngularJS really rocks!  well, most of the time 🙂

-TY

 

 

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s