将$ index与AngularJS'ng-options'指令一起使用? [英] Using $index with the AngularJS 'ng-options' directive?
问题描述
说我使用以下方法将数组绑定到select
标记:
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">
在这种情况下,为关联的option
标签分配了一系列索引值:(0、1、2,...).但是,当我从下拉列表中选择某项时,selData
的值将绑定到undefined
.绑定实际上应该起作用吗?
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">
在这里,option
标记获得相同的索引,但是整个对象都在更改时绑定.它是按设计方式工作的,还是这种行为仅仅是AngularJS的一个不错的bug或副作用?
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?
推荐答案
$ index是为ng-repeat而不是select定义的.我认为这解释了undefined
. (所以,不,这不应该.)
$index is defined for ng-repeat, not select. I think this explains the undefined
. (So, no, this shouldn't work.)
Angular支持在整个对象上进行绑定.该文档的措词可以更好地表明这一点,但是它确实暗示了这一点:当您希望将选择模型绑定到非字符串值时,应使用ngOptions ...而不是ngRepeat."
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."
这篇关于将$ index与AngularJS'ng-options'指令一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!