具有动态值和条件的ng-class

时间:2013-06-07 10:54:48

标签: angularjs

在我的控制器中有2个vars跟踪表的排序状态:

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

在css中有3个不同的类代表排序状态:

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

我想使用ng-class表达式动态更改表colums上的排序图标,这是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>

这是一种可能的实施方式(不是很聪明)

<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>

1 个答案:

答案 0 :(得分:2)

你应该分开这些类,一个用于.sorting,另一个用于.asc和.desc,比如

.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 */ }

然后将ng-class应用于映射

<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>