AngularJS orderBy date

房东的猫 提交于 2019-12-23 02:36:24

问题


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

回答1:


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.




回答2:


This should work for you:

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



回答3:


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



来源:https://stackoverflow.com/questions/32080669/angularjs-orderby-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!