Angular orderBy如何与日期字符串?

时间:2016-12-31 07:20:49

标签: angularjs

Angular orderBy与日期字符串的关系如何? 我正在尝试使用orderBy对ng-repeat进行排序。 我们的数据目前使用valueList作为过滤器,它不起作用。

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

$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>

2 个答案:

答案 0 :(得分:0)

您可以按日期排序,例如:

<!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>

答案 1 :(得分:0)

我建议使用自定义过滤器,例如:

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

对于orderby日期的写入逻辑,您可以使用moment.js

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

如果您有问题联系