假设我使用以下内容将数组绑定到select
标记:
<select ng-model="selData" ng-options="$index as d.name for d in data">
在这种情况下,为关联的option
标记分配一系列索引值:(0,1,2,...)。但是,当我从下拉列表中选择某些内容时,selData
的值将绑定到undefined
。绑定是否真的有效?
另一方面,请说我改为:
<select ng-model="selData" ng-options="d as d.name for d in data">
这里,option
标签获得相同的索引,但整个对象在更改时绑定。它是按设计方式工作的,还是这个行为只是一个很好的bug或AngularJS的副作用?
答案 0 :(得分:196)
由于数组与JavaScript中的对象非常相似,因此可以使用“对象数据源”的语法。诀窍在于ng-options
部分的括号:
var choices = [
'One',
'Two',
'Three'
];
在模板中:
<select
ng-model="model.choice"
ng-options="idx as choice for (idx, choice) in choices">
</select>
最后,model.choice
的值为0,1或2.当它为0时,您会看到One
; 1将显示Two
等。但在模型中,您将只看到索引值。
我在PACKT Publishing的“使用AngularJS掌控Web应用程序开发”中修改了此信息,并在Angular reference documentation for select进行了验证。
答案 1 :(得分:45)
由于您无法使用$index
,但可以尝试indexOf
。
<强> HTML 强>
<div ng-app ng-controller="MyCtrl">
<select
ng-model="selectedItem"
ng-options="values.indexOf(selectedItem) as selectedItem for selectedItem in values"></select>
selectedItem: {{selectedItem}}
</div>
<强>控制器强>
function MyCtrl($scope) {
$scope.values = ["Value1","Value2"];
$scope.selectedItem = 0;
}
演示 Fiddle
注释:
IE7(8)不支持 Array.prototype.indexOf
答案 2 :(得分:21)
$ index是为ng-repeat定义的,而不是选择。我认为这解释了undefined
。 (所以,不,这不应该奏效。)
Angular支持绑定整个对象。文档可以更好地表明这一点,但它暗示了它:“当你想要将select模型绑定到非字符串值时,应该使用ngOptions ...而不是ngRepeat。”
答案 3 :(得分:4)
您还可以使用ng-value =&#39; $ index&#39;在<option>
标记中。
<select ng-model="selData">
<option ng-repeat="d in data track by $index" ng-value="$index">
{{d.name}}
</option>
</select>
答案 4 :(得分:1)
请勿在select标记内使用$index
。如果要将数组索引用作值或选项,请在选项标记内使用$index
。
<option ng-repeat="user in users" value="{{user.username}}">{{$index+1}}</option>
如果要使用内部值,只需将其作为绑定表达式(如
)放在value属性中<option ng-repeat="user in users" value="{{$index+1}}">{{user.username}}</option>
我的控制器代码如下:
var users = ['username':'bairavan', 'username':'testuser'];