I am trying to order an array of objects by using a comparator
function, but it seems the comparator
function is completely ignored (See the angular documentation).
I am using angularJS 1.5.6.
Here is a JSFiddle
Html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.6/angular.min.js">
</script>
<body ng-app="app" ng-controller="ctrl">
{{msg}}
</body>
JavaScript:
angular.module("app", [])
.factory('f1', function($filter) {
var f1 = {};
function comparator(a,b) { console.log(a,b); return a.id - b.id; }
function getter(x) { /*console.log(x);*/ return x; }
f1.testOrderBy = function() {
return $filter('orderBy')(
[ {id:3}, {id:1}, {id:2} ],
getter,
false,
comparator
)
.map(function(x) { return x.id; })
};
return f1;
})
.controller("ctrl", function($scope, f1) {
$scope.msg = f1.testOrderBy();
})
My question: Why is comparator
ignored? (This can be seen since the console.log()
call is never made). Is this an angularJS bug?
Because of this I cannot even order an array of objects using a custom comparator.
Thanks!
Definition and Usage The orderBy filter allows us to sort an array. By default, strings are sorted alphabetically, and numbers are sorted numerically.
AngularJS orderBy filter allows sorting of data in a collection. It supports both, ascending and descending order. The "+" operator is used to order the data in ascending order and thde "-" operator is used to order the data in descending order.
To sort in descending order, set it as true . You can also use + to sort the data in an ascending and – the data in descending order also . Here with the filters in Angular JS, instead of displaying the various rows, we will be sorting it by ascending and descending order .
String: If the array is an array of objects, you can sort the array by the value of one of the object properties. See the examples below. Function: You can create a function to organize the sorting. Array: Use an array if you need more than one object property to determine the sorting order.
Because the support for custom comparators in orderBy
was added in 1.5.7.
You can read the changelog here.
If you check the documentation for 1.5.6 you will see that the api is described as:
$filter('orderBy')(array, expression, reverse)
While in 1.5.7 it is:
$filter('orderBy')(collection, expression, reverse, comparator)
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