Jim Cote Jim Cote - 4 months ago 32
AngularJS Question

AngularJS - Using $index in ng-options

If 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">


The OPTION tags get the expected incrementing index values (0, 1, 2, ...). However, when I select something from the dropdown, the value of
selData
is getting bound to
undefined
. Should the binding actually work?

On the other hand, if I do the following:

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


The OPTION tags get the same index, but the entire object is bound on change. I don't know if Angular is meant to support this, or if it's simply a nice bug/side effect.

Answer

$index is defined for ng-repeat, not select. I think this explains the undefined. (So, no, this shouldn't work.)

Angular supports binding on the entire object. The documentation could be worded better to indicate this, but it does hint at it: "ngOptions ... should be used instead of ngRepeat when you want the select model to be bound to a non-string value."