ng-repeat 上的 Angularjs OrderBy 不起作用 [英] Angularjs OrderBy on ng-repeat doesn't work
问题描述
我正在尝试将 AngularJS 用于我的第一个项目(锦标赛经理),并且 ng-repeat
上的 orderBy
过滤器不起作用:( 我已阅读所有相关文档,但无事可做:/
I'm trying to use AngularJS for my first project (a tournaments manager) and the orderBy
filter on ng-repeat
doesn't work :( I have read all the documentation about that, but nothing to do :/
所以,我在 $scope
上定义了变量:
So, I have vars defined on $scope
like that :
$scope.order_item = "count_win";
$scope.order_reverse = false;
$scope.teams = {
100 : {
id: 100,
name: "XXX",
count_win: 1,
count_loose: 2,
goal_average: 1,
},
200 : {
id: 200,
name: "XXX",
count_win: 1,
count_loose: 2,
goal_average: 1,
},
[...]
};
现在,在我看来,我正在尝试重新排序(首先只有一个订单项)但从不工作...
Now, on my view i'm trying to reorder (first with only one order item) but never work...
<tr ng-repeat="team in teams | orderBy:order_item:order_reverse">
<td>{{team.name}}</td>
<td>{{team.count_loose}}</td>
<td>{{team.goal_average}}</td>
</tr>
第二次,我想从 2 条信息中重新排序:count_win
和 goal_average
如果第一个相等......我尝试替换 $scope.order_item
就像这样,但如果有一个代码不起作用,他将永远不会使用 2...
The second time, I want to reorder from 2 pieces of information: count_win
and goal_average
if first are equal.. I try to replace $scope.order_item
like that, but if with one the code doesn't work, he'll never work with 2...
$scope.order_item = ['count_win','goal_average'];
感谢大家的阅读,对于帖子的大小感到抱歉.
Thank you all for reading and sorry for the post size.
推荐答案
$scope.teams
不是数组(它是对象的对象),orderBy
> filter 只适用于数组.如果你让 $scope.teams
成为一个数组,它会起作用:
$scope.teams
isn't an array (it's an object of objects), and the orderBy
filter only works with arrays. If you make $scope.teams
an array, it will work:
$scope.teams = [
{
id: 100,
name: "team1",
count_win: 3,
count_loose: 2,
goal_average: 2,
},
{
id: 200,
name: "team2",
count_win: 3,
count_loose: 2,
goal_average: 1,
},
{
id: 300,
name: "team3",
count_win: 1,
count_loose: 2,
goal_average: 1,
}
];
或者,您可以添加一个对对象起作用的特殊过滤器,如下所示(借自 这里):
Or, you can add a special filter that works on objects, like this (borrowed from here):
app.filter('orderObjectBy', function() {
return function(items, field, reverse) {
var filtered = [];
angular.forEach(items, function(item) {
filtered.push(item);
});
filtered.sort(function (a, b) {
return (a[field] > b[field] ? 1 : -1);
});
if(reverse) filtered.reverse();
return filtered;
};
});
像这样使用它:
<tr ng-repeat="team in teams | orderObjectBy:order_item:order_reverse">
请注意,此自定义过滤器不适用于您问题的第二部分中的排序顺序数组.
Note that this custom filter will not work with an array of sort orders as in the second part of your question.
这篇关于ng-repeat 上的 Angularjs OrderBy 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!