ng-repeat
とng-if
の代わりに、ng-repeat
にフィルタを使用して、$インデックスに必要な値が表示されます。
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};
});
OUTPUT:
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
JSFIDDLE。