关于angularjs:Angular-以ng-repeat排序对象

Angular - Sort objects in ng-repeat

我有如下angular对象:

1
2
3
4
5
6
7
var objs = {
   "1" : {name:'abc',createdAt:'2016-06-25'}
   "4" : {name:'abc',createdAt:'2015-07-06'}
   "7" : {name:'abc',createdAt:'2015-03-12'}
   "2" : {name:'abc',createdAt:'2016-01-04'}
   "6" : {name:'abc',createdAt:'2016-06-17'}
}

我想按属性" createdAt" DESC顺序对这些obj进行ng-repeat排序(orderBy)。

Please Note down that objs is of type Object not Array. I am iterating over objects.

如何实现?

1
2
3
<tr ng-repeat="obj in objs track by $index | orderBy : createdAt : true">
    <td>{{obj.createdAt}}</td>
</tr>

我是否应该使用$ index?

这里是plnkr


内置的orderBy不适用于对象,但有人为您要执行的操作创建了过滤器:

http://justinklemm.com/angularjs-filter-ordering-objects-ngrepeat/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
yourApp.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="item in items | orderObjectBy : 'createdAt' : true">

https://plnkr.co/edit/3lbvJCegtHYIougIhK1R?p=preview


如果您添加订单,则会收到错误消息:

1
2
orderBy:notarray
Value is not array-like

幸运的是,角误差参考手册将提供以下建议:

orderBy must be used with an array-like value so a subset of items can
be returned. The array can be initialized asynchronously and therefore
null or undefined won't throw this error.

To use orderBy to order the properties of an object, you can create
your own array based on that object:

1
2
  $scope.arrFromMyObj = Object.keys(myObj).map(function(key) {
    return myObj[key];   }); });

完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<html ng-app="SoApp">
  <head>

  </head>
  <body>
  <table ng-controller="appCtrl">
    <tr ng-repeat="value in data| orderBy:'createdAt':true">
      <td>{{value.createdAt}}</td>
    </tr>
  </table>

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js">
 
    angular.module('SoApp', [])
    .controller('appCtrl', ['$scope',
      function($scope) {
        $scope.objs = {
         "1" : {name:'abc',createdAt:'2016-06-25'},
         "4" : {name:'abc',createdAt:'2015-07-06'},
         "7" : {name:'abc',createdAt:'2015-03-12'},
         "2" : {name:'abc',createdAt:'2016-01-04'},
         "6" : {name:'abc',createdAt:'2016-06-17'}
        };
        $scope.data =  Object.keys($scope.objs).map(function (key) {return $scope.objs[key]});
        console.log($scope.arrFromMyObj )
      }]);
 

  </body>
</html>