嵌套的ng-repeat $ parent.$ index和$ index [英] nested ng-repeat $parent.$index and $index
问题描述
我有一个奇怪的错误,不幸的是,我无法使用jsfiddle复制.除了以下代码段,我已经注释掉了我的整个代码(库等).有什么明显的我不明白的地方吗?有什么想法吗?
I have a strange bug that, unfortunately, I cannot replicate with jsfiddle. I've commented out my entire code (Except libraries,etc) except for the following snippets. Is there something obvious that I don't understand? Any ideas?
这有效并打印:(0,0)(0,1)(1,0)(1,1)
This works and prints: (0,0) (0,1) (1,0) (1,1)
<div ng-repeat="i in list">
<div ng-repeat="j in list2">
<div>
({{$parent.$index}} {{$index}})
</div>
</div>
</div>
但是,这段代码显示:(0,0)(1,1)(0,0)(1,1)
However, this piece of code prints: (0,0) (1,1) (0,0) (1,1)
<div ng-repeat="i in list">
<div ng-repeat="j in list2">
<div ng-if="1">
({{$parent.$index}} {{$index}})
</div>
</div>
</div>
我的控制器是:
$scope.list = [1, 2];
$scope.list2 = [1, 2];
推荐答案
DEMO FIDDLE
这是因为指令ng-if
为自身创建了一个新作用域,当您引用$parent
时,它访问了直接$parent
的作用域,即内部重复表达式的作用域.
That's because the directive ng-if
creates a new scope for itself, when you refer to $parent
, it access the immediate $parent
's scope, i.e., the inner repeat expression's scope.
因此,如果您想实现以前的目标,可以使用以下方法:
So if you want to achieve something you wanted like in the former, you may use this:
<div ng-repeat="i in list">
<div ng-repeat="j in list2">
<div ng-if="1">
({{$parent.$parent.$index}} {{$parent.$index}})
</div>
</div>
</div>
如果您有多个内部指令,则可以使用ng-init
将$index
存储在变量中,以供子作用域中的引用使用.
if you have more than one inner directives, you can use ng-init
for storing $index
in a variable for references in child scopes.
<div ng-repeat="i in list" ng-init="outerIndex=$index">
<div ng-repeat="j in list2" ng-init="innerIndex=$index">
<div ng-if="1">
({{outerIndex}} {{innerIndex}})
</div>
</div>
</div>
我强烈建议您阅读了解角度范围的文章
这篇关于嵌套的ng-repeat $ parent.$ index和$ index的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!