【问题标题】:How Angular orderBy with date string?Angular orderBy 如何使用日期字符串?
【发布时间】:2016-12-31 15:42:43
【问题描述】:

Angular orderBy 如何使用日期字符串? 我正在尝试使用 orderBy 对 ng-repeat 进行排序。 我们的数据当前将 valueList 用于不起作用的过滤器。

我相信他们是按字母数字排序而不是按日期排序,因为我的“matchDate”字段是一个字符串。 我的问题是,如何最好地将此字段转换为日期以便正确排序

$scope.valueList=
[
    {
        "_id" : ObjectId("5862c276d9913952fa80aa11"),
        "matchDate" : "31 December, 2016",
        "scoreStatus" : "OPEN"
    },
    {
        "_id" : ObjectId("58679badd991390f83fbb994"),
        "matchDate" : "30 December, 2016",
        "scoreStatus" : "CLOSE"
    },
    {
        "_id" : ObjectId("58679badd991390f83fbb994"),
        "matchDate" : "28 December, 2016",
        "scoreStatus" : "OPEN"
    }
]

这是我的html

<div ng-repeat="eachValue in valueList | orderBy: 'matchDate'">
    {{eachValue.matchDate}}
</div>

【问题讨论】:

标签: angularjs


【解决方案1】:

你可以像这个例子一样按日期排序:

<!DOCTYPE html>
 <html lang="en-US">
   <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
   <body>
    <script type="text/javascript">
       angular.module('app',[]).controller('test',function($scope){
         $scope.valueList=[{
         "_id" : "5862c276d9913952fa80aa11",
         "matchDate" : "31 December, 2016",
         "scoreStatus" : "OPEN"
        },{
         "_id" : "58679badd991390f83fbb994",
         "matchDate" : "30 December, 2016",
         "scoreStatus" : "CLOSE"
       },{
         "_id" : "58679badd991390f83fbb994",
         "matchDate" : "28 December, 2016",
         "scoreStatus" : "OPEN"
     }]

         $scope.myValueFunction = function(date) {
            return new Date(date) 
         };
     })
    </script>
    <div ng-app="app" ng-controller="test">
      <div ng-repeat="eachValue in valueList | orderBy: myValueFunction">
        {{eachValue.matchDate}}
      </div>
     </div>
  </body>
</html>

【讨论】:

    【解决方案2】:

    我建议使用这样的自定义过滤器:

    app.filter('orderByDate', function() {
      return function(items) {
        // write your logic for order by  date
        // then return results as items    items= results;
        return items;
      };
    });
    

    orderby date的写逻辑可以使用moment.js

    <div ng-repeat="eachValue in valueList | orderByDate>
        {{eachValue.matchDate}}
    </div>
    

    如有问题联系

    【讨论】:

    • 如何将此日期格式转换为时刻,请帮助我
    猜你喜欢
    • 1970-01-01
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多