Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

orderBy array item value in Angular ng-repeat

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?

like image 610
tuff Avatar asked Jul 29 '13 23:07

tuff


1 Answers

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

like image 186
Blackhole Avatar answered Sep 21 '22 19:09

Blackhole