Javascript ng repeat和$index在外部和内部循环中
我的控制器中有这样一个数组:Javascript ng repeat和$index在外部和内部循环中,javascript,angularjs,arrays,Javascript,Angularjs,Arrays,我的控制器中有这样一个数组: $scope.myArray = [ { id: 1, name: "my object", options: [ { id: 1, key: "key1", value: "value1" }, { id: 2, key: "key2", value: "value2"
$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"
}
]
}
]
我想在我的模板中循环使用angular。这就是我到目前为止所做的:
<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>
/*如何在这里再次使用$index循环遍历选项数组?$index不是用于父循环吗*/
我的问题是,在我试图使用obj.options[$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“obj In myArray”时,它表示“obj”是数组中正在迭代的当前项的别名。尝试以下操作:
<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“obj In myArray”时,它表示“obj”是数组中正在迭代的当前项的别名。
$index
将始终为您提供当前的ng repeat
索引。要获取父级ng repeat
索引,请使用$parent.$index
$index
将始终为您提供当前ng repeat
索引。要获取父级ng repeat
索引,请使用$parent.$index
尝试以下方法:要从两个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>
如果您想从这两个位置获取索引,请尝试以下操作:
<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>
如果您做错了,请使用@MichaelAlckwedelgårdo提供的解决方案如果您做错了,请使用@MichaelAlckwedelgårdThx提供的解决方案。正是我需要的。谢谢。正是我需要的,我理解你的答案。但我对使用$index感兴趣,因为我希望使用双向数据绑定,将值准确地保存在作用域中,以便将它们发送到服务器进行编辑。如果我只执行ng model=option,那么当我想将整个阵列重新发送到服务器以保存(如果进行了编辑)时,它将不起作用。希望这能解释。我想它也会起作用。因为option.value绑定到obj.options[$index]。value和object.name绑定到myArray[$index]。name。($index始终是当前作用域中的一个)@codegeek此解决方案将100%适用于双向绑定。我理解您的答案。但我对使用$index感兴趣,因为我希望使用双向数据绑定,将值准确地保存在作用域中,以便将它们发送到服务器进行编辑。如果我只执行ng model=option,那么当我想将整个阵列重新发送到服务器以保存(如果进行了编辑)时,它将不起作用。希望这能解释。我想它也会起作用。因为option.value绑定到obj.options[$index]。value和object.name绑定到myArray[$index]。name。($index始终是当前作用域中的一个)@codegeek此解决方案将100%使用双向绑定。