Using $index with the AngularJS ‘ng-options’ directive?

Since arrays are very similar to objects in JavaScript, you can use the syntax for “object data sources”. The trick is in the brackets in the ng-options part:

var choices = [
  'One',
  'Two',
  'Three'
];

In the template:

<select
  ng-model="model.choice"
  ng-options="idx as choice for (idx, choice) in choices">
</select>

In the end, model.choice will have the value 0, 1, or 2. When it’s 0, you will see One; 1 will display Two, etc. But in the model, you will see the index value only.

I adapted this information from “Mastering Web Application Development with AngularJS” by PACKT Publishing, and verified at the Angular reference documentation for select.

Leave a Comment