Reputation: 1947
The data I am receiving from a webservice is formatted as dd/mm/yyyy. The problem with this is when sorting, it sorts by dd rather than yyyy.
<td ng-repeat="thead in resultHeader">
<a href="" ng-click="order(thead.line)">{{thead.head}}</a>
<span class="sortorder" ng-show="predicate === thead.line" ng-class="{reverse:reverse}"></span>
</td>
Controller:
$scope.order = function(predicate) {
var results = $scope.model.resultList;
$scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
$scope.predicate = predicate;
$scope.model.currentPage = 1;
$scope.model.beginFrom = 0;
};
How can I sort this data by yyyy with my current set up?
{
"name": "Test",
"ShipmentDate": "06\/08\/2012"
}
Upvotes: 4
Views: 2125
Reputation: 2687
Use the custom order for this. Look:
function MyCtrl($scope, orderByFilter) {
$scope.sortedFriends = [
{
name: 'John',
age: 25,
dateTest: '10/10/2015'
}, {
name: 'Jimmy',
age: 25,
dateTest: '10/12/2015'
},{
name: 'Mary',
age: 28,
dateTest: '10/09/2009'
}, {
name: 'Ed',
age: 27,
dateTest: '30/03/2014'
},{
name: 'Andrew',
age: 27,
dateTest: '11/11/2016'
}];
$scope.orderByCustom = function(friend) {
console.log(friend)
return friend.dateTest.split('/')[2];
};
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app ng-controller="MyCtrl">
<ul>
<li ng-repeat="friend in sortedFriends | orderBy:orderByCustom"">
{{friend}}
</li>
</ul>
</div>
Upvotes: 2
Reputation: 2655
The key part is to add a $filter
to your module and use that $filter to get the Date
value from the string. you can use Date.parse('dd/mm/yyyy')
to get the time in float, and then run an Array.sort() to your data.
Upvotes: 3
Reputation: 6420
If you converted your date strings to Date
objects, you can use the orderBy:
filter to sort by date.
<td ng-repeat="thead in resultHeader | orderBy:'ShipmentDate':shouldBeReversedOrder ">
<a href="" ng-click="shouldBeReversedOrder = !shouldBeReversedOrder">{{thead.head}}</a>
<span class="sortorder" ng-show="predicate === thead.line" ng-class="{reverse:reverse}"></span>
</td>
When you want to display the date back in a proper formate you can use {{thead.ShipmentDate | 'yyyy-mm-dd'}}
to format it for you.
Upvotes: 2