Angular.js: $parent.$index lost when using ng-if

Created on 10 Sep 2015  ·  3Comments  ·  Source: angular/angular.js

My HTML Code

<div>
  <ul>
    <li ng-repeat='parentItem in arr1'>
      <div ng-repeat='childItem in arr2'>
        {{ $parent.$index }} , {{ $index }}
      </div>
    </li>
  </ul>
</div>

Javascript code inside controller

$scope.arr1 = [1,2];
$scope.arr2 = [1,2];

This code giveing me correct answer

0, 0
0, 1
1, 0,
1, 1

But if I use ng-if="true" in child loop then it giving me wrong answer

<div>
  <ul>
    <li ng-repeat='parentItem in arr1'>
      <div ng-repeat='childItem in arr2' ng-if="true">
        {{ $parent.$index }} , {{ $index }}
      </div>
    </li>
  </ul>
</div>
0, 0
1, 1
0, 0
1, 1

This was wrong. It change parent index to child index

Please fix this issue

Most helpful comment

This is not an issue in Angular. This happens (as documented), because ngIf creates a new scope, so $parent does not refer to the scope of the outer ngRepeat.

That is why using $parent is not a good practice here. You could/should use ngInit to create an alias of the parent index, like this:

<li ng-repeat="parentItem in arr1" ng-init="parentIdx = $index">
  <div ng-repeat="childItem in arr2" ng-if="true">
    {{ parentIdx }} , {{ $index }}
  </div>
</li>

Demo

All 3 comments

This is not an issue in Angular. This happens (as documented), because ngIf creates a new scope, so $parent does not refer to the scope of the outer ngRepeat.

That is why using $parent is not a good practice here. You could/should use ngInit to create an alias of the parent index, like this:

<li ng-repeat="parentItem in arr1" ng-init="parentIdx = $index">
  <div ng-repeat="childItem in arr2" ng-if="true">
    {{ parentIdx }} , {{ $index }}
  </div>
</li>

Demo

BTW, this is a general support question. Such questions should better be directed to the appropriate channels.
GitHub issues are reserved for bug reports and feature requests.

Thanks,

I can use this by ng-init

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ceymard picture ceymard  ·  3Comments

ashish91 picture ashish91  ·  3Comments

guyandtheworld picture guyandtheworld  ·  3Comments

jtorbicki picture jtorbicki  ·  3Comments

michael-letcher picture michael-letcher  ·  3Comments