Domanda

How do you use the orderBy filter to reverse an array of Dates? I can use .sort().reverse() on the model itself, but I'd rather let angular do it if possible

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>

Expected Result

Feb 1, 2013 12:00:00 AM
Jan 1, 2013 12:00:00 AM

According to the docs, I'd expect to be able to do it like this, but it didn't work

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

Soluzione

You can't use d in orderBy, because this variable doesn't exist when the filter is applied : the array is first filtered, and only then is "repeated".

You must sort the array by each item's actual value. See 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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top