Angular - 以ng-repeat排序对象

时间:2016-07-15 06:31:54

标签: angularjs angularjs-ng-repeat ng-repeat

我有如下角度物体:

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'对ng-repeat中的 objs 进行排序(orderBy) DESC命令。

  

请注意,objs的类型为对象而不是数组。我正在迭代对象。

如何实现这一目标?

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

我应该使用$ index吗?

这是 plnkr

2 个答案:

答案 0 :(得分:1)

内置orderBy无法处理对象,但有人为您要执行的操作创建了一个过滤器:

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

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 :(得分:0)

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

orderBy:notarray
Value is not array-like

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

  

orderBy必须与类似数组的值一起使用,以便项目的子集可以   被退回该数组可以异步初始化,因此   null或undefined不会抛出此错误。

     

要使用orderBy来排序对象的属性,您可以创建   基于该对象的您自己的数组:

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

完整代码:

<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"></script>
  <script>
    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 )
      }]);
  </script>

  </body>
</html>
相关问题