Skip to content

Aquent | DEV6

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages

AngularJS Custom orderBy Function

Written by: Chad Upton

AngularJS makes it very easy to sort and filter basic data, but the AngularJS documentation is a bit light when it comes to creating a custom orderBy function for sorting.

Lets say you’re building the next great fantasy football league and you want to display a list of players and sort those players by their win percentage. The database contains the wins and losses, but you want to sort by the percentage. Lets use a custom orderBy function to do that.

For a custom orderBy function, the AngularJS docs say:

Getter function. The result of this function will be sorted using the <, =, > operator.

That means your custom orderBy function will be called for each item in your ng-repeat and it should return a number that will be used to determine that item’s position in the list — it’s location in he list will be ordered by that number. These functions can be fairly complex depending on your sort logic. In this case, we’ll just divide losses by wins to get the win percentage. The function will return that number causing the list to be sorted based on that number.

$scope.playerSortFunction = function(player) {
    return player.losses / player.wins;

I have created a JSFiddle to show the HTML, JavaScript and Result of this:

When looking at the JSFiddle example, notice that the order of names in the javascript is different from the result in the bottom right — this change in order is the custom orderBy function at work.


Sign up for our Angular Course

Learn the most recent version and start building your own Angular apps

view course details