Ng-Options In Angular

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.
  1. $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.
  1. <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.
  1. <option value="?" selected="selected" label=""></option>  
  2. <option value="0" label="SSC">SSC</option>  
  3. <option value="1" label="Intermediate">Intermediate</option>  
  4. <option value="2" label="Graduation">Graduation</option>  
  5. <option value="3" label="Post-Graduation">Post-Graduation</option>  
  6. <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.
  1. <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 -
  1. <option value="?" selected="selected" label=""></option>  
  2. <option value="SSC" label="SSC">SSC</option>  
  3. <option value="Intermediate" label="Intermediate">Intermediate</option>  
  4. <option value="Graduation" label="Graduation">Graduation</option>  
  5. <option value="Post-Graduation" label="Post-Graduation">Post-Graduation</option>  
  6. <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 
  1. $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.
  1. <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.
Ebook Download
View all
Learn
View all