Ng - if you call $ parent. $ index must be set to $ index

I have a ng repeater with a nested ng repeater contained within it. In a nested relay I am trying to keep track of the $ index value, it works fine. However, when I injected ng-if on the same element that has a reference to $ parent. $ Index, the parent index is set to the child index. Any ideas on this? The code works here . For example, I click on index 1 of parent 0 and get index 1 of parent 1 as indices.

JavaScript

var myApp = angular.module('myApp', []);

myApp.controller('ctrl', function($scope) {

  $scope.arr = [["a","b","c"],["d","f","e"],["f","h","i"]];

  $scope.logIndex = function(index, parent) {
    console.log("index: " + index + ", parent: " + parent);
  };

});

      

Html

<ul>
  <li ng-repeat="i in arr">
    <ul>
      <li ng-repeat="j in i">
         <span ng-click="logIndex($index, $parent.$index)" ng-if="$index > 0">{{ j }}</span>
      </li>
    </ul>
  </li>
</ul>

      

+3


source to share


1 answer


This is because it ng-if

creates a child in the element, so $parent

it is actually its immediate child ng-repeat scope, not its parent, and the $ index is again the same $ index inherited from its immediate parent (i.e. the second child ng-repeat object). You can use ng-init

ng-repeat to alias custom properties and use that property instead of using $ parent.

   <li ng-repeat="i in arr" ng-init="parentIndex=$index">
    <ul>
      <li ng-repeat="j in i">
         <span ng-click="logIndex($index, parentIndex)" ng-if="$index > 0">{{ j }} </span>
      </li>
    </ul>
   </li>

      



Demo

+4


source







All Articles