将 $index 与 AngularJS 'ng-options' 指令一起使用? [英] Using $index with the AngularJS 'ng-options' directive?

查看:22
本文介绍了将 $index 与 AngularJS 'ng-options' 指令一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我使用以下命令将数组绑定到 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 的一个不错的错误或副作用?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆