在AngularJS'ng-options'指令中使用$ index?

Jim*_*ote 59 html-select angularjs

假设我select使用以下内容将数组绑定到标记:

<select ng-model="selData" ng-options="$index as d.name for d in data">
Run Code Online (Sandbox Code Playgroud)

在这种情况下,为关联的option标签分配一系列索引值:(0,1,2,...).但是,当我从下拉列表中选择某些内容时,其值将selData被绑定undefined.绑定实际上是否有效?

另一方面,说我改为做以下事情:

<select ng-model="selData" ng-options="d as d.name for d in data">
Run Code Online (Sandbox Code Playgroud)

这里,option标签获得相同的索引,但整个对象在更改时绑定.它是通过设计这种方式工作,还是这种行为只是一个很好的bug或AngularJS的副作用?

Har*_*nen 197

由于数组与JavaScript中的对象非常相似,因此可以使用"对象数据源"的语法.诀窍在部分的括号ng-options:

var choices = [
  'One',
  'Two',
  'Three'
];
Run Code Online (Sandbox Code Playgroud)

在模板中:

<select
  ng-model="model.choice"
  ng-options="idx as choice for (idx, choice) in choices">
</select>
Run Code Online (Sandbox Code Playgroud)

最后,model.choice将具有值0,1或2.当它为0时,您将看到One; 1将显示Two等.但在模型中,您将只看到索引值.

我从PACKT Publishing的"使用AngularJS掌控Web应用程序开发"中修改了这些信息,并在Angular参考文档中进行了验证.

  • 如果你需要````idx```是一个数字,只需将它乘以1并将其解析为int.```idx*1作为选择```中的(idx,choice)的选择 (35认同)
  • 设置预选选项时,此方法似乎不起作用.虽然在UI中手动选择时,ngModel显然会获得一个数字,但您无法预先选择为ngModel分配索引.似乎是AngularJS中的错误或非预期用途.毕竟它是非阵列的技巧 (7认同)
  • 聪明的把戏.正是我需要的,除了模型设置为字符串而不是数字. (5认同)

Max*_*tin 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>
Run Code Online (Sandbox Code Playgroud)

调节器

function MyCtrl($scope) {
    $scope.values = ["Value1","Value2"];
    $scope.selectedItem = 0;
}
Run Code Online (Sandbox Code Playgroud)

演示 Fiddle

评论:

Array.prototype.indexOf IE7不支持(8)


Mar*_*cok 21

$ index是为ng-repeat定义的,而不是选择.我认为这解释了undefined.(所以,不,这不应该奏效.)

Angular支持绑定整个对象.文档可以更好地表明这一点,但它暗示了它:"当你想要将select模型绑定到非字符串值时,应该使用ngOptions ...而不是ngRepeat."