I am looking to sort the output of an ng-repeat
displaying objects based on their specific "id" property. The order in which I want them to appear is stored in an array, so I created a custom filter like this:
ng-repeat="line in dataObject|objectIdFilter:orderByArray"
:
.filter('objectIdFilter', [function() {
return function(inputObjet, orderArray) {
var result = [];
angular.forEach(orderArray, function(value) {
result.push(inputObjet[value]);
});
console.log(result);
return result;
}
}])
Here is a basic example controller that includes the objects and the order id in an array:
.controller('MainCtrl', ['$scope', function($scope) {
$scope.dataObject = {
1: {username:'user1'},
10: {username:'user10'},
20: {username:'user20'},
500: {username:'user500'}
};
$scope.orderByArray = [20,10,1,500];
}])
With the corresponding HTML code:
<div ng-app="myApp">
<div ng-controller="MainCtrl">
<div ng-repeat="line in dataObject|objectIdFilter:orderByArray">{{line.username}}</div>
</div>
</div>
Jsfiddle: https://jsfiddle.net/infnadanada/tLrx4uro/
So...
Everything is functioning correctly, but I am unsure if there is another method to sort the ng-repeat as I did without resorting to a custom filter.
Additionally, if you check the browser console on the Jsfiddle link provided, you may notice that my custom filter appears to be returning the result twice and I am uncertain as to why.
PS: English is not my first language :D
Thank you!