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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With