orderBy two fields (one in reverse)

All we need is an easy explanation of the problem, so here it is.

I would like to order a friend list by status (online firsts, offline lasts) and by alphabetical order. All I manage to get is:

  • Online firsts / Reversed alphabetical order
  • Or offline firsts / Alphabetical order

Here is plunker to expose my problem

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Change the orderBy filter to this:


This will order by descending status (by prefixing the - character), then ascending name. Currently you’re passing true to reverse the sort, which is causing the status to be correct (online first), but the names to be reversed (i.e., descending).

If you want to keep the reverse boolean, you could use orderBy:['status','-name']:true but that seems less clear than just making status descending as shown earlier.

Method 2

There is another option to do that, you can have multiple orderBy filter in ng-repeat and that line :

<li class="friend" ng-repeat="friend in friends | orderBy:['status','name']:true">

will be :

<li class="friend" ng-repeat="friend in friends | orderBy:'name':false | orderBy:'status':true">

The last orderBy is execute first and the second to last etc …

Here is my plunkr : http://plnkr.co/edit/girPFzdi3Zx0yp0ASGVQ?p=preview

Method 3

In Angular 1.5.8 previous example does not work.
Different logic has to be applied.

It looks logic from previous orderBy is applied to the next one, so in order to sort name ASC and status DESC name order has to be reveresed:

<li class="friend" ng-repeat="friend in friends | orderBy:'name':true | orderBy:'status':true">

Here is fixed example: http://plnkr.co/edit/0ZFIftSgNkU9F03xJztG?p=preview

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply