ng-repeat没有正确显示键顺序

时间:2015-10-14 19:54:45

标签: json angularjs indexing key ng-repeat

我有一个具有不同命名键的对象,每个键都有自己的字符串数组,如下所示。但是,我无法按照我想要的方式使用ng-repeat进行排序。我想这样做的方式

ng-repeat="(key, value) in $scope.myModel | orderBy: key"

我意识到这是因为ng-repeat不允许通过密钥进行排序,并且我必须拥有一个不会改变的特定命名密钥,并且为了做到这一点而重复。无论如何我可以通过ng-repeat正确地对JSon对象进行排序吗?  我希望它看起来像这样:

10/14/2015 1:30:00 PM: Array[14]
10/14/2015 9:30:00 AM: Array[14]
10/5/2015 9:30:00 PM: Array[14]
10/6/2015 9:30:00 PM: Array[14]
10/7/2015 9:30:00 PM: Array[14]

使用

显示时的样子
ng-repeat="(key, value) in $scope.myModel"

10/5/2015 9:30:00 PM: Array[14]
10/6/2015 9:30:00 PM: Array[14]
10/7/2015 9:30:00 PM: Array[14]
10/14/2015 1:30:00 PM: Array[14]
10/14/2015 9:30:00 AM: Array[14]

2 个答案:

答案 0 :(得分:0)

过滤器orderBy: key在这里没用,因为您的输入是一个对象。您无法保证对象中的订单。来自orderBy documentation

  

通过表达式谓词对指定的数组进行排序。

如果您想要保证订单,则必须将$scope.myModel转换为数组。

答案 1 :(得分:0)

我会在你使用ng-repeat之前准备数据你可以通过抓取对象键,对它们进行排序并使用它们来创建一个新的排序对象来做到这一点。 这是一个有效的插件http://plnkr.co/edit/CktRzgo7je40gBxXILKi?p=info

//js
  $scope.myModel =  {
    "10/14/2015 1:30:00 PM" : [1,2,3,4,5,6,7,8,9,10,11,12,13,14],
    "10/14/2015 9:30:00 AM" : [1,2,3,4,5,6,7,8,9,10,11,12,13,14],
    "10/5/2015 9:30:00 PM" : [1,2,3,4,5,6,7,8,9,10,11,12,13,14],
    "10/6/2015 9:30:00 PM" : [1,2,3,4,5,6,7,8,9,10,11,12,13,14],
    "10/7/2015 9:30:00 PM" : [1,2,3,4,5,6,7,8,9,10,11,12,13,14]
  };

  $scope.mySortedModel = {};

  $scope.myModelSortedKeysAsc = Object.keys($scope.myModel).sort(function(a,b){
       return new Date(a) - new Date(b);
  });

   $scope.myModelSortedKeysAsc.forEach(function(el){

       $scope.mySortedModel[el] = $scope.myModel[el];
   });

   // html 

   <div  ng-repeat="(key, value) in mySortedModel">
      {{key}--{{value}}
  </div>
相关问题