问题
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?
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>
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>
My controller is:
$scope.list = [1, 2];
$scope.list2 = [1, 2];
回答1:
DEMO FIDDLE
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>
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>
I strongly suggest you to go through this article on understanding scopes in angular
回答2:
Instead of using ng-init
you can use the (key, value)
ng-repeat
syntax to get the parent index.
DEMO
<div ng-repeat="(iKey, i) in list">
<div ng-repeat="j in list2">
<div ng-if="1">
({{iKey}} {{$index}})
</div>
</div>
</div>
回答3:
check out the PLUNK
ng-if is creating a new child scope because of which there is a need to add $parent.
i have created myname
property which tells the scope name, using which you can check whats exactly happening..
<div ng-if="1">
({{$parent.$parent.$index}} {{$parent.$index}})
</div>
回答4:
The ng-if
introduce an another scope, so one $parent.
isn't enough.
You could double it like this $parent.$parent.$index
, or remember the index of the outer ng-repeat
in a different variable via ng-init
like this:
<div ng-repeat="i in list" ng-init="listIndex = $index">
<div ng-repeat="j in list2">
<div ng-if="1">
({{listIndex}} {{$index}})
</div>
</div>
</div>
Example plunker: http://plnkr.co/edit/dtaBAmkU32BCsLASLs0C?p=preview
来源:https://stackoverflow.com/questions/25094201/nested-ng-repeat-parent-index-and-index