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?
Don't use
$index
inside select tags. Use$index
inside the option tags if you want to use the array indexes as either values or options.If you want to use inside values just put it in the value attribute as binding expression like
and my controller code be like:
Since you can't use
$index
but you can tryindexOf
.HTML
Controller
Demo Fiddle
Comment:
Array.prototype.indexOf
is not supported in IE7 (8)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:In the template:
In the end,
model.choice
will have the value 0, 1, or 2. When it's 0, you will seeOne
; 1 will displayTwo
, 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.
You can also use ng-value='$index' in
<option>
tag.$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."