angularjsangularjs-orderby

AngularJS orderBy date


I have something like this:

  <div ng-repeat="i in inv">
      <p>{{i.dueDate}}</p>
  </div>

I'd like to order by oldest date first. I know there's a way to do it but I can't figure it out. Can anyone help?

Here is the sample js:

 $scope.inv = [
    {
        name: "Paul",
        dueDate: "5/21/2014"
    },
    {
        name: "Dan",
        dueDate: "5/22/2014"
    },
    {
        name: "Randy",
        dueDate: "1/12/2015"
    }
 ];

Solution

  • You have to define a customizer function, then use it in orderBy expression. For example:

    $scope.dueDateFormatter = function(i) {
       var dateParts = i.dueDate.split(/\//);
       return dateParts[2] 
           + '-' + (dateParts[0] < 10 ? '0' + dateParts[0] : dateParts[0]) 
           + '-' + (dateParts[1] < 10 ? '0' + dateParts[1] : dateParts[1]);
    };
    
    <div ng-repeat="i in inv | orderBy:dueDateFormatter">
       <p>{{i.dueDate}}</p>
    </div>
    

    Demo. The function basically reorders the date string, so that Year comes first, Month next and Day last. If you use moment.js or similar library, you can use their parsers instead.