Angular 1.x:OrderBy未排序日期

时间:2019-01-24 02:32:17

标签: angularjs angularjs-directive

如何使用“过滤器”方法按升序或降序对日期进行排序?

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> 
</script>
<body>
<div ng-app="myApp" ng-controller="orderCtrl">
<ul><li ng-repeat="x in dates | orderBy">{{x}}</li></ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('orderCtrl', function($scope) {
$scope.dates = ["01/02/2018", "02/02/2018", "06/06/2018", "01/22/2019",     "12/12/2018"];
});
</script>
</body>
</html>

获取为     01/02/2018     2019/01/22     02/02/2018     2018/06/06     2018/12/12

输出异常     01/02/2018     02/02/2018     2018/06/06     12/12/2018     2019/01/22

1 个答案:

答案 0 :(得分:1)

您需要将字符串转换为日期并进行排序

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> 
</script>
<body>
<div ng-app="myApp" ng-controller="orderCtrl">
<ul><li ng-repeat="x in dates | orderBy : sort : false">{{x}}</li></ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('orderCtrl', function($scope) {
$scope.dates = ["01/02/2018", "02/02/2018", "06/06/2018", "01/22/2019","12/12/2018"];
$scope.sort = function(date) {
    var date = new Date(date);
    return date;
};
});
</script>
</body>
</html>