[英]ng-repeat and $index in outer and inner loop
我的控制器中有一个像这样的数组:
$scope.myArray = [
{
id: 1,
name: "my object",
options: [
{
id: 1,
key: "key1",
value: "value1"
},
{
id: 2,
key: "key2",
value: "value2"
}
]
},
{
id: 2,
name: "my object 2",
options: [
{
id: 1,
key: "key3",
value: "value3"
},
{
id: 2,
key: "key4",
value: "value4"
}
]
}
]
我想在我的模板中以角度循环浏览。 这是我到目前为止的内容:
<div ng-repeat="obj in myArray">
<input ng-model="myArray[$index].name" />
<div ng-repeat="option in obj.options">
/*How can I use $index again here to loop through the options array ? Wouldn't $index be for the parent loop */
<input ng-model="obj.options[$index].value" />
</div>
</div>
我的问题是,在上面的内部循环中,我尝试使用obj.options[$index]
,这将指向options数组的正确索引,还是仍然认为它正在使用父数组的索引?
$index
将始终为您提供当前的ng-repeat
索引。 要获取父级ng-repeat
索引,请使用$parent.$index
尝试这个:
<div ng-repeat="obj in myArray">
<input ng-model="obj.name" />
<div ng-repeat="option in obj.options">
<input ng-model="option" />
</div>
</div>
在Angular中,当您使用ng-repeat“ myArray中的obj”时,它指出“ obj”是要在数组中迭代的当前项的别名。
试试这个,你想从两个ng-repeat中获取索引:
<div ng-repeat="(indexParent, obj) in myArray">
<input ng-model="myArray[indexParent].name" />
<div ng-repeat="(index,option) in obj.options">
<input ng-model="myArray[indexParent].options[index].value" />
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.