使用角度orderBy过滤器来反转日期数组

时间:2013-10-21 16:53:41

标签: angularjs angularjs-orderby

如何使用orderBy过滤器来反转日期数组?我可以在模型本身上使用.sort().reverse(),但我更愿意让角度尽可能

http://jsfiddle.net/V6aZH/2/

JS

var myApp = angular.module('myApp', []);

myApp.controller('DatesCtrl', ['$scope', function($scope) {
    $scope.dates = [ new Date(2013, 0, 1), new Date(2013, 1, 1) ];
}]);

HTML

<div ng-controller="DatesCtrl">
    <div ng-repeat="d in dates" ng-bind="d | date:'medium'"></div>
</div>

预期结果

2013年2月1日12:00:00 AM 2013年1月1日上午12:00:00

根据文档,我希望能够像这样做,但它不起作用

<div ng-controller="DatesCtrl">
    <div ng-repeat="d in dates | orderBy:'d':true" ng-bind="d | date:'medium'"></div>
</div>

1 个答案:

答案 0 :(得分:1)

您不能在d中使用orderBy,因为在应用过滤器时此变量不存在:首先过滤数组,然后才“重复”。

您必须按每个项目的实际值对数组进行排序。见this question

$scope.identity = angular.identity;
$scope.dates = [new Date(2013, 0, 1), new Date(2013, 2, 1), new Date(2013, 1, 1)];

<div ng-repeat="d in dates | orderBy:identity:true" ng-bind="d | date:'medium'"></div>

Fiddle

相关问题