Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
366 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...