1

In my controller there are 2 vars keeping track of sorting status of a table:

/* sorting */
$scope.sortField = 'code';
$scope.sortDir = 'asc';

In the css there are 3 different classes representing the sorting status:

table.table thead .sorting { ...} /*sorting disabled*/
table.table thead .sorting_asc { ... } /*sorting asc*/
table.table thead .sorting_desc { ... } /*sorting desc*/

I would like to use a ng-class expression to dynamically change the sorting icon on my table colums, this is the html:

<thead>
  <tr>
    <th ng-class="" ng-click="sortBy('code')">Summit code</th>
    <th ng-class="" ng-click="sortBy('name')">Name</th>
    <th ng-class="" ng-click="sortBy('height')">Height</th>
    <th ng-class="" ng-click="sortBy('points')">Points</th>
  </tr>
</thead>

This is a possible implementation (not very clever)

<thead>
  <tr>
    <th ng-class="{sorting_asc: (sortField == 'code' && sortDir == 'asc'), sorting_desc: (sortField == 'code' && sortDir == 'desc'), sorting: (sortField != 'code')}"  ng-click="sortBy('code')">Summit code</th>
    <th ng-class="{sorting_asc: (sortField == 'name' && sortDir == 'asc'), sorting_desc: (sortField == 'name' && sortDir == 'desc'), sorting: (sortField != 'name')}" ng-click="sortBy('name')">Name</th>
    <th ng-class="{sorting_asc: (sortField == 'height' && sortDir == 'asc'), sorting_desc: (sortField == 'height' && sortDir == 'desc'), sorting: (sortField != 'height')}" ng-click="sortBy('height')">Height</th>
    <th ng-class="{sorting_asc: (sortField == 'points' && sortDir == 'asc'), sorting_desc: (sortField == 'points' && sortDir == 'desc'), sorting: (sortField != 'points')}" ng-click="sortBy('points')">Points</th>
  </tr>
</thead>
gabric
  • 1,865
  • 2
  • 21
  • 32
  • check this: http://stackoverflow.com/questions/7792652/what-is-the-best-way-to-conditionally-apply-a-class-with-angularjs – bingjie2680 Jun 07 '13 at 11:07

1 Answers1

2

You should separate the classes, one for .sorting, end the other for .asc and .desc, like

.sorting {  /* sorting disabled */ }
.sorting.asc   {   /* put the asc icon, will inherit everything else from sorting */ }
.sorting.desc   {   /* put the desc icon, will inherit everything else from sorting */ }

and then apply the ng-class with a mapping

<thead>
  <tr>
    <th ng-class="{sorting: (sortField == 'code'), asc: (sortDir == 'asc'), desc: (sortDir == 'desc')}" ng-click="sortBy('code')">Summit code</th>
    <th ng-class="" ng-click="sortBy('name')">Name</th>
    <th ng-class="" ng-click="sortBy('height')">Height</th>
    <th ng-class="" ng-click="sortBy('points')">Points</th>
  </tr>
</thead>
rewritten
  • 16,280
  • 2
  • 47
  • 50