目前,如果我过滤,$ index也会更新。因此,如果有500个结果,我过滤排名,也会更新。我如何拥有一个不会更新的索引列?
这是我的代码:
<input ng-model="query.teamName" /></div>
<table class="table">
<thead>
<tr>
<th>Rank</th>
<th>Team</th>
<th>Location</th>
<th>Score</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="team in teams | filter:query | orderBy:orderByScore:reverseSort">
<td><span style="color:white">{{$index+1}}</span></td>
<td>{{team.teamName}}</td>
<td>{{team.teamLocation}}</td>
<td>{{team.teamPoints | number:2}}</td>
</tr>
</tbody>
</table>
控制器:
scoreboard.controller('scoreboardCtrl', function ($scope, $filter) {
$scope.orderByScore = 'teamPoints';
$scope.reverseSort = true;
$scope.teams = [
{ "teamName": "motorboat skydive", "teamLocation": "1189 King", "teamPoints": 35.53},
{ "teamName": "the grinders", "teamLocation": "1189 King", "teamPoints": 127.90},
{ "teamName": "team forrec", "teamLocation": "1189 King", "teamPoints": 29.46},
{ "teamName": "bikini finger", "teamLocation": "1189 King", "teamPoints": 21.98},
{ "teamName": "la familia", "teamLocation": "1189 King", "teamPoints": 148.32},
{ "teamName": "darkness is", "teamLocation": "1189 King", "teamPoints": 108.88},
{ "teamName": "grinders", "teamLocation": "1189 King", "teamPoints": 167.95},
{ "teamName": "discarded youth", "teamLocation": "1189 King", "teamPoints": 55.52}
];
};
答案 0 :(得分:5)
Angular过滤器删除并添加一个新数组并更新ng-repeat,因此$index
也将更新。相反,您可以初始化索引ng-init="idx=$index+1"
并使用它。 ng-init
值永远不会被观看,也不会更新,但$index
将根据数组中项目的迭代次数进行更改
<tr ng-repeat="team in teams | filter:query | orderBy:orderByScore:reverseSort" ng-init="idx = $index+1">
<td><span>{{idx}}</span></td>
<强> Plnkr 强>
由于索引在你的情况下是至关重要的,因为它是排名最好的方法来处理这个可能是从控制器本身添加索引。
$scope.teams = [
{ "teamName": "motorboat skydive", "teamLocation": "1189 King", "teamPoints": 35.53},
{ "teamName": "the grinders", "teamLocation": "1189 King", "teamPoints": 127.90},
{ "teamName": "team forrec", "teamLocation": "1189 King", "teamPoints": 29.46},
{ "teamName": "bikini finger", "teamLocation": "1189 King", "teamPoints": 21.98},
{ "teamName": "la familia", "teamLocation": "1189 King", "teamPoints": 148.32},
{ "teamName": "darkness is", "teamLocation": "1189 King", "teamPoints": 108.88},
{ "teamName": "grinders", "teamLocation": "1189 King", "teamPoints": 167.95},
{ "teamName": "discarded youth", "teamLocation": "1189 King", "teamPoints": 55.52}
]
.sort(function(itm1, itm2){ return itm2.teamPoints - itm1.teamPoints }) //Sort teams
.map(function(itm, idx){ itm.index = (idx+1); return itm; }); //assign rankings
我使用本机排序或者只是在控制器中使用角度orderByFilter本身为初始集合执行(并从视图中删除ng-init变量赋值的逻辑)。因此,您不会运行运行时$ index问题。
<强> Plnkr2 强>