How to access the index of super parent in nested

2019-09-10 07:40发布

问题:

I want to access the index of the outermost ng-repeat.

<div ng-repeat="">
  <div ng-repeat="">
    <div ng-repeat="">
      //I want to get the $index of outer ng-repeat here
    </div>
  </div>
</div>

回答1:

Use ng-init to set the outer index:

<div ng-repeat="" ng-init="outerIndex = $index">

Then you can use outerIndex in the other scopes.

Angular documentation has this example specifically



回答2:

A nice clean way to do this is with ng-init

<div ng-repeat="" ng-init="indxFirst = $index">
 <div ng-repeat="" ng-init="indxSecond = $index">
   <div ng-repeat="">
       //the current index $index
      //indxFirst is your the parent most index
      <div ng-click="myClick(indxFirst)">Check most outer parent index</div>
   </div>
 </div>
</div>

So, for example I added a click function and passed it inside the inner most repeat, and in the controller you would see it passed here like :

$scope.myClick = function(index){
   console.log("parent most index is", index);
};

Can use it however you like, this is just an example.