10

Consider the following nested ng-repeat directives:

  <tr ng-repeat="r in SomeExpr1">
    <td ng-repeat="c in SomeExpr2">
      <p>c index is {{$index}}, r index is {{???}}</p>
    </td>
  </tr>

How can I access the $index of the outer ng-repeat (i.e., the one in the parent scope that is hidden by the inner ng-repeat scope $index)?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Patrice Chalin
  • 15,440
  • 7
  • 33
  • 44
  • Is there a way to do this in AngularDart `1.0.0`? Using `$parent` results in a `NoSuchMethodError` as it is trying to find an instance getter in the component. – Scotty Waggoner Oct 11 '14 at 08:01

2 Answers2

17

As @Randal Schwartz pointed out in this post $parent does the trick.

<div ng-controller='demo-ctrl'>
  <div ng-repeat="row in ctrl.matrix">
    <div ng-repeat="column in row">
      <span>outer: {{$parent.$index}} inner: {{$index}}</span>
    </div>

  </div>
</div>
Randal Schwartz
  • 39,428
  • 4
  • 43
  • 70
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
5

You need ng-init from Angular.js. Sadly, that hasn't been ported yet, but it would look like this if it worked:

<script>
  function Ctrl($scope) {
    $scope.list = [['a', 'b'], ['c', 'd']];
  }
</script>
<div ng-controller="Ctrl">
  <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
    <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
       <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
    </div>
  </div>
</div>

(via http://docs.angularjs.org/api/ng/directive/ngInit)

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Randal Schwartz
  • 39,428
  • 4
  • 43
  • 70
  • 1
    ng-init is not planned https://github.com/angular/angular.dart/issues/128 but it should be easy to add a custom directive that stores this value to make it reusable in the inner repeat – Günter Zöchbauer Feb 18 '14 at 15:54
  • 1
    Well, I withdraw my request for ng-init, even though it makes demos a bit easier. :) Happy to just put my init in my controller, and use $parent to get to the next-outer $index. Case CLOSED. – Randal Schwartz Feb 19 '14 at 14:25
  • I really don't know about angular.dart but, in plain angular :P you should really use $parent.$index as it's not really safe. The example @RandalSchwartz its safer... If you add an ng-if inside the loop, you get the $index messed, check: http://plnkr.co/52oIhLfeXXI9ZAynTuAJ – Gonz Dec 10 '14 at 05:08