Get the $ index of an ng-repeat that contains an ng-controller in $ scope in AngularJS

3

I have an application that uses ng-repeat to list information. So:

HTML

<div ng-controller="listaCtrl">
    <div ng-repeat="item in lista" ng-controller="itemCtrl">
        <pre>{{item}}</pre>
    </div>
</div>

I'm using this example for work on each item in the list, and I need to know the index that this ng-repeat contains within my itemCtrl .

Is there any method to get the $ index of ng-repeat inside my controller?

    
asked by anonymous 22.01.2016 / 14:35

1 answer

5

Use the constant $index normally, it is referenced in the parent scope. The sample below demonstrates this behavior:

function listCtrl($scope) {
  
  $scope.items = [{name:'a'},{name:'b'},{name:'c'}];
  
}

function itemCtrl($scope) {
  
  console.log('Index atual:' + $scope.$index);
  
}
<html ng-app>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script></head><body><divng-controller="listCtrl">
      <div ng-repeat="i in items" ng-controller="itemCtrl">
        <pre>{{$index}} - {{i}}</pre>
      </div>      
    </div>
  </body>
</html>

The result on the console is as follows:

Index atual:0
Index atual:1
Index atual:2
    
22.01.2016 / 15:10