tuff tuff - 1 year ago 39
Javascript Question

orderBy array item value in Angular ng-repeat

How can I get Angular's

directive to sort a list by each item's actual value, rather than by the value of a property on each item?


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

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

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


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