角度数组循环和排序函数

时间:2016-07-25 16:58:19

标签: javascript arrays angularjs loops sorting

我有一个对象数组,每个对象包含以下属性:

comments:""
id:1
inProgress:false
jobDescription:null
lastUpdateDate:"07/08/2016"
lastUpdatedByUser:"xxx@abc.com"
product:"Chicken"
status:Object
templateName:"Standard Template"
uploadDate:"07/08/2016 10:36:01"

我需要一个角度函数,我可以在整个列表中循环并对uploadDate进行排序,并使用最新的第一个等等。

我尝试过使用它,但它不起作用:

vm.uploads = $filter('orderBy')(vm.uploads, vm.uploads[0].uploadDate, reverse);

2 个答案:

答案 0 :(得分:2)

Array.prototype.sort就够了:

vm.uploads.sort(function(a,b){
   return  new Date(a.uploadDate).getTime()- new Date(b.uploadDate).getTime();
})

如果您想要desc订单,只需切换a& b

答案 1 :(得分:1)

您的语法错误,您应该这样称呼它:

vm.uploads = $filter('orderBy')(vm.uploads, 'uploadDate', true)

看看这个简单的演示



(function() {
  angular
    .module('app', [])
    .controller('MainCtrl', MainCtrl);

  function MainCtrl($filter) {
    var vm = this;

    vm.reverse = false;
    vm.uploads = [  
       {  
          "comments":"",
          "id":1,
          "inProgress":false,
          "jobDescription":null,
          "lastUpdateDate":"07/08/2016",
          "lastUpdatedByUser":"xxx@abc.com",
          "product":"Chicken",
          "status":1,
          "templateName":"Standard Template",
          "uploadDate":"07/08/2016 10:36:01"
       },
       {  
          "comments":"",
          "id":2,
          "inProgress":true,
          "jobDescription":null,
          "lastUpdateDate":"08/08/2016",
          "lastUpdatedByUser":"xxx@abc.com",
          "product":"Horse",
          "status":1,
          "templateName":"Custom Template",
          "uploadDate":"08/08/2016 12:49:05"
       }
    ];

    vm.order = function () {
      vm.uploads = $filter('orderBy')(vm.uploads, 'uploadDate', vm.reverse = !vm.reverse);
    }
  }
})();

<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
</head>

<body ng-controller="MainCtrl as main">
  <ul>
    <li ng-repeat="upload in main.uploads track by $index" ng-bind="upload.uploadDate"></li>
  </ul>
  <hr>
  <button type="button" value="order" ng-click="main.order()">Change order</button>
</body>

</html>
&#13;
&#13;
&#13;

我建议您查看docs