Using $index with the AngularJS 'ng-options' directive?

Jim Cote picture Jim Cote · Dec 17, 2012 · Viewed 75.1k times · Source

Say that I bind an array to a select tag using the following:

<select ng-model="selData" ng-options="$index as d.name for d in data">

In this case, the associated option tags are assigned a sequence of index values: (0, 1, 2, ...). However, when I select something from the drop-down, the value of selData is getting bound to undefined. Should the binding actually work?

On the other hand, say that I instead do the following:

<select ng-model="selData" ng-options="d as d.name for d in data">

Here, the option tags get the same index, but the entire object is bound on change. Is it working this way by design, or this behavior simply a nice bug or side-effect of AngularJS?

Answer

Harry Pehkonen picture Harry Pehkonen · Feb 27, 2014

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.