目前,如果我过滤,$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","teamPoints": 127.90},{ "teamName": "team forrec","teamPoints": 29.46},{ "teamName": "bikini finger","teamPoints": 21.98},{ "teamName": "la familia","teamPoints": 148.32},{ "teamName": "darkness is","teamPoints": 108.88},{ "teamName": "grinders","teamPoints": 167.95},{ "teamName": "discarded youth","teamPoints": 55.52} ]; };
解决方法
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>
由于索引在你的情况下是至关重要的,因为它是排名最好的方法来处理这可能是从控制器本身添加索引.
$scope.teams = [ { "teamName": "motorboat skydive","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问题.