1

Using Angular 1.0.7, how can I specify a single index for nested ng-repeats, so that each item on the inner arrays get's a consecutive index value? (i.e. 0, 1, 2, 3 and so on for all elements in all inner arrays)

To illustrate:

<ul>
    <li ng:repeat="item in arr1">
        <ul>
            <li ng:repeat="child in item.children">{{consecutiveIndex++}}</li>
        </ul>
    </li>
</ul>

I tried to achieve it in the following manner:

var cindex= -1;
$scope.cindex= function () {
  console.log('cindex', cindex);
  return ++cindex;
};

HTML:

<ul>
    <li ng:repeat="item in arr1">
        <ul>
            <li ng:repeat="child in item.children">{{index()}}</li>
        </ul>
    </li>
</ul>

I am getting quite exotic AngularJS errors using this (believe me, you don't wanna know).

I have also found out (following the console output), that even for an array with a mere 4 elements, ng-repeat hit my cindex() function over 80 times. Meaning instead of 0, 1, 2 and 3 - I got 84, 85, 86 and 87.

Any ideas?

2 Answers 2

4

You can't depend on your {{index()}} to be called a fixed amount of times. Whenever angular decides to dirty check a scope it will run all the bindings.

You can generate the value based on other indexes. Demo plunker

HTML

<body ng:controller="MainCtrl">
  <ul>
     <li ng:repeat="item in arr1">
        <ul ng:init="parentIndex = $index">
           <li ng:repeat="child in item.children">{{getConsecutiveIndex(parentIndex, $index)}}</li>
        </ul>
     </li>
  </ul>
</body>

JS

app.controller('MainCtrl', function($scope) {
  $scope.arr1 = [{children:[0,1,2,3]}, {children:[4,5]}, {children:[6,7,8]}];

  $scope.getConsecutiveIndex = function(parentIndex, $index) {
    var total = 0;
    for(var i = 0; i < parentIndex; i += 1) {
      total += $scope.arr1[i].children.length;
    }
    return total + $index;
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, for sharing this. I had a similar requirement, nested ng-repeats, but needed to know which iteration of the outer $index I was in. I was able to move the ng-init to the same tag as the outer ng-repeat. FYI.
1

The ngRepeat directive provides a special $index property which should suit your needs. It is zero-based and is exposed on the local scope of each template instance.

Try this:

<ul>
    <li ng:repeat="item in arr1">
        <ul>
            <li ng:repeat="child in item.children">{{$index + 1}}</li>
        </ul>
    </li>
</ul>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.