Angularjs OrderBy on ng-repeat doesn't work

萝らか妹 提交于 2019-11-28 19:08:52
Jerrad

$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;
  };
});

And use it like this:

<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.

Balthazar

You don't have to create a scope parameter for your orderBy, you can directly do this in your markup if you are dealing with arrays.

<tr ng-repeat="team in teams | orderBy:count_win:false">

With two parameters, you should just do

<tr ng-repeat="team in teams | orderBy:['count_win','goal_average']">

After for a more complex order, you could create a function in your scope like so :

$scope.customOrder = function (team) {
    //custom
}

And just call it like

<tr ng-repeat="team in teams | orderBy:customOrder">

Like @Jerrad said, ng-repeat only works with arrays, so you need to convert your teams object into an array to get it work properly.

meberhard

ng-repeat works only on arrays, not on JSON objects. This was already discussed here: Angular - Can't make ng-repeat orderBy work

You either have to change the JSON object to an Array, or to convert it on the fly. The controller could then look like this:

var app = angular.module('app', []);

app.controller('Ctrl', function ($scope) {

    $scope.teams = [
        {
            id: 100,
            name: "A Team",
            count_win: 1,
            count_loose: 2,
            goal_average: 1
        },
        {
            id: 200,
            name: "C Team",
            count_win: 2,
            count_loose: 3,
            goal_average: 4
        },
        {
            id: 300,
            name: "B Team",
            count_win: 4,
            count_loose: 1,
            goal_average: 8
        }
    ];
    $scope.predicate = 'name';
});

I created a fiddle here with a demo containing your data:

http://jsfiddle.net/c3VVL/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!