Angularjs Nested Ng-repeats With A Single Index?
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 a
Solution 1:
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
<bodyng:controller="MainCtrl"><ul><ling:repeat="item in arr1"><ulng:init="parentIndex = $index"><ling: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;
}
});
Solution 2:
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><ling:repeat="item in arr1"><ul><ling:repeat="child in item.children">{{$index + 1}}</li></ul></li></ul>
Post a Comment for "Angularjs Nested Ng-repeats With A Single Index?"