目前,我有以下常见循环
<div ng-repeat=
<li ng-if=
--> {{$index}} </br>
使用$index
并不符合我的需要,因为它会打印出来
--> 1
--> 2
--> 5
--> 9
...
我希望打印出来
--> 1
--> 2
--> 3
--> 4
...
如何手动跟踪计数器?
答案 0 :(得分:4)
而不是使用ng-repeat
和ng-if
将ng-repeat
与过滤器一起使用,然后$ index将显示您想要的值。
HTML:
<div ng-app="app">
<div ng-controller="ctrl as vm">
<span>Your Approach:</span>
<div ng-repeat="item in vm.items">
<div ng-if="item > 5">
<span>Item: {{item}}. $index: {{$index}}</span>
</div>
</div>
<br/>
<span>Filter Approach:</span>
<div ng-repeat="item in vm.items | filter:vm.greaterThanFiveFilter">
<span>Item: {{item}}. $index: {{$index}}</span>
</div>
</div>
</div>
JS:
angular.module('app', []).
controller('ctrl', function() {
this.items = [1, 2, 3, 4, 5, 6, 7, 8, 9];
this.greaterThanFiveFilter = function(item){ return item > 5};
});
输出:
Your Approach:
Item: 6. $index: 5
Item: 7. $index: 6
Item: 8. $index: 7
Item: 9. $index: 8
Filter Approach:
Item: 6. $index: 0
Item: 7. $index: 1
Item: 8. $index: 2
Item: 9. $index: 3