nested ng-repeat $parent.$index and $index

Jason picture Jason · Aug 2, 2014 · Viewed 51.5k times · Source

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];

Answer

Raghavendra picture Raghavendra · Aug 2, 2014

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