Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 241
Floris Avatar asked Jun 17 '16 09:06

Floris


People also ask

What is orderBy filter in AngularJS?

Definition and Usage The orderBy filter allows us to sort an array. By default, strings are sorted alphabetically, and numbers are sorted numerically.

How to sort in descending order in AngularJS?

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.

How to use sorting in AngularJS?

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 .

How do I sort an array in AngularJS?

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.


1 Answers

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)
like image 95
tasseKATT Avatar answered Oct 18 '22 20:10

tasseKATT