AngularJS orderBy date

2019-06-07 22:40发布

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

3条回答
Viruses.
2楼-- · 2019-06-07 22:50

you need to convert your strings to YYYY-MM-DD format

<li ng-repeat="item in inv | orderBy:orderByDate">{{item.name}} </li>

$scope.orderByDate = function(item) {
var parts = item.dueDate.split('/');
var date = new Date(parseInt(parts[2], parseInt(parts[0]), parseInt(parts[1])));

return date;

};

Demo http://plnkr.co/edit/o6fCDyiqkkU9YVWwZC09?p=preview

查看更多
劫难
3楼-- · 2019-06-07 22:51

This should work for you:

<div ng-repeat="i in inv | orderBy:'-dueDate'">
  <p>{{i.dueDate}}</p>
</div>
查看更多
乱世女痞
4楼-- · 2019-06-07 22:52

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.

查看更多
登录 后发表回答