Using Angular JS's ngRepeat
directive, how can I make it so that the resulting iterations go in the reverse order? I am using an object where the keys are numbers, and I'd like to sort by those, descending.
I know that you can't really sort an object by keys like this (without keeping a reference to an array), but is this at all possible with Angular?
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<body>
<script>
var app = angular.module('myApp', []);
app.filter('orderObjectBy', function() {
return function(items, field, reverse) {
var filtered = [];
angular.forEach(items, function(item) {
filtered.push(item);
});
filtered.sort(function(a, b) {
return (a[field] > b[field] ? 1 : -1);
});
if (reverse) filtered.reverse();
return filtered;
};
});
app.controller('myController', ['$scope',
function($scope) {
$scope.data = {
2013: 'oldest 4',
2014: 'older 3',
2015: 'new 2',
2016: 'newest 1'
};
}
]);
</script>
<div id="myApp" ng-app='myApp' ng-controller="myController">
<div ng-repeat="(date,text) in data">{{text}}</div>
<hr/>
<div ng-repeat="(date,text) in data | orderBy:date:reverse">{{text}}</div>
<hr/>
<div ng-repeat="(date,text) in data | orderBy:'-date'">{{text}}</div>
<hr/>
<div><b>Correct Answer!:</b></div><hr/>
<div ng-repeat="(date,text) in data | orderObjectBy:date:true">{{text}}</div>
</div>
</body>
For example, i'd like this to sort from Most recent to Oldest (the opposite of what it does in this code)
ng-repeat doen't work with object for it you need to create your custom filter.
<div ng-repeat="(date,text) in data | orderObjectBy:date:true">{{text}}</div>
app.filter('orderObjectBy', function() {
return function(items, field, reverse) {
var filtered = [];
angular.forEach(items, function(item) {
filtered.push(item);
});
filtered.sort(function (a, b) {
return (a[field] > b[field] ? 1 : -1);
});
if(reverse) filtered.reverse();
return filtered;
};
});
Plunker
Hope it helps :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With