Search code examples
javascripthtmlangularjsangularjs-orderby

Sorting Columns Using Angular With Priority


I am trying to use angular to sort my columns. I have got the code of the angular tutorial to work.

Now I am having trouble getting one row to always stay at the top. For example I will have one column called mainContact. Only one person can be set true for this value. I want the person with the mainContact as true always to stay at the top row of the table, while the others change with the sorting. I honestly am a little lost for ideas on how to do this.

I put together this to demonstrate what I have so far: http://jsfiddle.net/Beastwood/m44fy1j5/

<div ng-controller="ExampleController">
<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
 <table class="friend">
<tr>
  <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a></th>
  <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
  <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
    <th>MAIN CONTACT</th>
</tr>
<tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  <td>{{friend.name}}</td>
  <td>{{friend.phone}}</td>
  <td>{{friend.age}}</td>
     <td>{{friend.mainContact}}</td>
</tr>
</table>
</div>

JS FIle

var myApp = angular.module('myApp', [])
.controller('ExampleController', ['$scope', function($scope) {
  $scope.friends =
      [{name:'John', phone:'555-1212', age:10, mainContact:true},
       {name:'Mary', phone:'555-9876', age:19, mainContact:false},
       {name:'Mike', phone:'555-4321', age:21, mainContact:false},
       {name:'Adam', phone:'555-5678', age:35, mainContact:false},
       {name:'Julie', phone:'555-8765', age:29, mainContact:false}];
   $scope.predicate = '-age';
   }]);

Solution

  • You can pass an array of property names to the filter, and prefix a property name with - to reverse...

    <tr ng-repeat="friend in friends | orderBy:['-mainContact', (reverse ? '-' : '') + predicate]">
        ...
    </tr>
    
    • -mainContact - first sort by mainContact property in reverse order (because true = 1, false = 0)
    • (reverse ? '-' : '') + predicate - then sort by the predicate, appending a - if reverse is true

    Live Demo