32

How can I get Angular's ng-repeat directive to sort a list by each item's actual value, rather than by the value of a property on each item?

eg:

<ul>
    <li ng-repeat="item in items | orderBy:'WHAT_GOES_HERE??'">{{item}}</li>
</ul>

Here's a fiddle to play with: http://jsbin.com/okatur/1/edit

I realize I could just do .sort() on the array, but is that my only option?

tuff
  • 4,895
  • 6
  • 26
  • 43

2 Answers2

49

Since 1.3.0-rc.5

Since AngularJS 1.3.0-rc.5, the orderBy filter (see the documentation) will automatically sort the array using its items if no additional parameters are provided.

<li ng-repeat="item in items | orderBy">{{item}}</li>

JS Bin

Before 1.3.0-rc.5

The orderBy filter (see the historical documentation) can also take a function as second parameter, whose return value will be compared using the <, = and > operator. You can simply use the angular.identity (see the documentation) for that purpose:

$scope.identity = angular.identity;
<li ng-repeat="item in items | orderBy:identity">{{item}}</li>

JS Bin

Blackhole
  • 20,129
  • 7
  • 70
  • 68
  • Cool, thanks! Is it possible to refer to `angular.identity` directly in the markup, without having to save it to `$scope.identity` in the JS? – tuff Jul 30 '13 at 00:17
  • No. You can only access to variables defined in the `$scope` in the template. – Blackhole Jul 30 '13 at 00:25
  • Also worth noting that you can orderBy reverse with >1.3.0-rc.5 by using `orderBy:true:true` – Braden Steffaniak Jan 08 '17 at 05:29
  • 1
    @BradenSteffaniak Well, no, it doesn't work. Actually, since 1.3.0-rc.5, `array | orderBy` is equivalent to `array | orderBy:'+'`. If you want to sort in reverse order, you can therefore simply do `array | orderBy:'-'`. Give it a try with the first JS Bin link ;-) ! – Blackhole Jan 08 '17 at 16:43
5

You can try following.

<ul>
    <li ng-repeat="item in items | orderBy:'toString()'">{{item}}</li>
</ul>
Hearaman
  • 8,466
  • 13
  • 41
  • 58
Rahul Jujarey
  • 199
  • 1
  • 4