Ng-options is an attribute for selecting control types and is used to generate a list of options for selecting boxes dynamically.
However, we can use ng-repeat to render the options but ng-options has its own benefits with respect to render speed, flexibility, and memory consumption.
Using ng-options for simple array like array of strings
Let's say we have the following array.
- $scope.qualificationsList = [‘SSC’, ’Intermediate’, ’Graduation’, ’Post-Graduation’,’Doctorate’];
And if we want to show them in dropdown using ng-options, we can write the following snippet in our HTML.
- <select name="qualification" ng-model="selectedQualification" data-ng-options=" qualification as qualification for qualification in qualificationsList"></select>
And, we will get this result in HTML.
- <option value="?" selected="selected" label=""></option>
- <option value="0" label="SSC">SSC</option>
- <option value="1" label="Intermediate">Intermediate</option>
- <option value="2" label="Graduation">Graduation</option>
- <option value="3" label="Post-Graduation">Post-Graduation</option>
- <option value="4" label="Doctorate">Doctorate</option>
Ohh, I wonder why the value is showing 0,1,2… rather than what I provided in the array? If we want to have the value as what we provided in the array, we need to use the following.
- <select name="qualification" ng-model="selectedQualification" data-ng-options=" qualification as qualification for qualification in qualificationsList track by qualification"></select>
Now, this will result as -
- <option value="?" selected="selected" label=""></option>
- <option value="SSC" label="SSC">SSC</option>
- <option value="Intermediate" label="Intermediate">Intermediate</option>
- <option value="Graduation" label="Graduation">Graduation</option>
- <option value="Post-Graduation" label="Post-Graduation">Post-Graduation</option>
- <option value="Doctorate" label="Doctorate">Doctorate</option>
But ng-model will be assigned the right value anyway, even we don’t use track by.
Ng-options for array of custom data types
If we have an array of objects like
- $scope.qualificationsList = [{id : 1, name : 'SSC'},{id : 2, name : 'Intermediate'},{id : 3, name : 'Graduation'},{id : 4, name : 'Post-Graduation'},{id : 5, name : 'Doctorate'}];
And, if we want to show them in dropdown using ng-options, we can write the following snippet in our HTML.
- <select name="qualification" ng-model="selectedQualification" data-ng-options=" qualification.id as qualification.name for qualification in qualificationsList"></select>
In this case, when you click on option in dropdown, it shows the names of the object but internally, the id of the object will be mapped to model.