Get the $index of an ng-repeat that contains an ng-controller in $Scope in Angularjs

Asked

Viewed 12,988 times

6

I have an app that uses a ng-repeat to list information. Like this:

HTML

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

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

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

  • Catch the index when?

1 answer

9


Use the constant $index normally, it is referenced in the scope Parent. 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>
    <div ng-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
  • thanks partner, I was already imagining a lot of zucchini that I would have to play this as an input inside the controller block, and bla bla rs..

  • 1

    @Leandroluk Always a pleasure to help - the person from Angular did a good job, the number of really necessary gambiarras is minimal. ;)

  • without a doubt! to go out the Angular2 and begin to study it well (already has in fact but is still in beta)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.