0

I have an array of objects, each object contains the following properties:

comments:""
id:1
inProgress:false
jobDescription:null
lastUpdateDate:"07/08/2016"
lastUpdatedByUser:"[email protected]"
product:"Chicken"
status:Object
templateName:"Standard Template"
uploadDate:"07/08/2016 10:36:01"

I need a function in angular that I can loop through the entire list and sort through the uploadDate and have the most recent first, etc.

I tried using this but it did not work:

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

2 Answers 2

1

Array.prototype.sort is enough :

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

If you want desc order , just switch a & b

Sign up to request clarification or add additional context in comments.

Comments

1

Your have a syntax error, you should call it like this:

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

Take a look on this simple demo:

(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":"[email protected]",
          "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":"[email protected]",
          "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>

I'd recommend you to check the docs.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.