Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 679
Jim Cote Avatar asked Dec 17 '12 15:12

Jim Cote


1 Answers

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.

like image 107
Harry Pehkonen Avatar answered Sep 21 '22 09:09

Harry Pehkonen