Floris Floris - 5 months ago 258
AngularJS Question

Why does AngularJS `orderBy` filter ignore the `comparator` parameter?

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!

Answer

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)
Comments