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?

Answers:

Answer

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

Answer

You can try following.

<ul>
    <li ng-repeat="item in items | orderBy:'toString()'">{{item}}</li>
</ul>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.