Question

In angular.js 1.0.7 orderBy filter used with predicate string '.' reverses the array order.

For example:

$filter('orderBy')(['a','b','c'], '.'); // -> ['c', 'b', 'a'].

How one can explain the logic of the transformation?

Upd. answer already found by myself below.

Was it helpful?

Solution 3

So I finally found a sane explanation to my question, which was pretty simple, why this awkward behavior happens, not how it's meant or supposed to be written, or kinda things. I just debugged the source code calls in dev tools withing angular step by step and it turns out to be this:

Using

So it turns out that due to specificity of parsing mechanism in angular, '.' is eventually considered to be in this case a NaN and inside the sorting function of an array the last return v1 < v2 ? -1 : 1; defaults to false and we get 'return 1' which reverses our array order constantly.

You can yourself try [1,2,3].sort(function(a, b){return 1;}), the output will be [3,2,1].

Bingo.

Upd: in current version of angular there is a correctly thrown error on such behavior:

Error: $parse:syntax : Token '.' not a primary expression at column 1 of the expression [.] starting at [].

OTHER TIPS

I cannot replicate using AngularJS 1.2.16. With a simple app the orderBy makes no modification to the input set:

Normal Order

a
b
c
d
e

Reverse Order

a
b
c
d
e

PLUNKER EXAMPLE: http://embed.plnkr.co/jn8PHVrgUHqAYjApWMKd

Note that the controller also includes a commented statement that changes the order of $scope.abc to not follow natural ordering. Even with this change, there's no effect on the output.

For more info you can look through the source of orderBy too: https://github.com/angular/angular.js/blob/master/src/ng/filter/orderBy.js#L78

playing around a little

<ul>
    <li ng-repeat="i in abc | orderBy:'.'">{{i}}</li>

</ul>
<ul>
    <li ng-repeat="i in abc | orderBy">{{i}}</li>
</ul>

this does the trick, it has something to do with the expression and the fact that the array has primitive values. not sure why

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top