logan Sarav logan Sarav - 2 months ago 12
Javascript Question

Sort data in Single column on the table based on the Heading in Angular

What I am working on is to perform sort operation in a table on a single or multiple columns. Let's assume that we have a table like this.

enter image description here

On clicking on Heading 1 only the Data 1 and Data 2 should be sorted when clicking on the Heading 2 the Data 3 and Data 4 need to be sorted.

Have implemented simple sort for the table in Angular, but cannot get an idea how to implement this one with two sets of data in a single column.

Even tried separate tables since the order by in Angular is based on the key in the array, both(Data 1,2,3 & 4) are getting updated when clicking on the Heading 1.

ng-repeat is used to form the table

Can anyone point me in the right direction(on Angular 1.x)?

Sample Fiddle
http://jsfiddle.net/ANEA6/13/

Answer Source

The problem is that you're using the same variable to handle the reverse!

<div ng-controller="MyCtrl">
  <table class="table">
    <tr class="heading">
      <td ng-click="reverse1=!reverse1;predicate1='id'">id</td>
    </tr>
    <tr ng-repeat="user in users | orderBy:predicate1:reverse1">
      <td>{{user.id}}</td>
    </tr>
    <tr class="heading">
      <td ng-click="reverse2=!reverse2;predicate2='id'">id</td>
    </tr>
    <tr ng-repeat="user in users | orderBy:predicate2:reverse2">
      <td>{{user.id}}</td>
    </tr>
  </table>
</div>

You can check this working fiddle ==> http://jsfiddle.net/ANEA6/17/