使用ng-repeat在angularJS中排序时显示已排序的图标

时间:2014-11-07 18:52:50

标签: angularjs angular-ngmodel

我无法在列的排序中显示正确的图标,如果单击一列进行排序,则所有其他列的图标也会更新。
只有排序列才能获得有关各列排序的更新。
我在此处列出了我的代码:http://plnkr.co/edit/UonOgNz0s16iKJkWLwyg?p=preview

HTML代码:

  <table border="1">
    <thead>
      <tr>
        <th ng-repeat="key in getKeysOfCollection(colors[0])" ng-click="ctrl.predicate = key; ctrl.reverse=!ctrl.reverse;">
          {{key}}
          <span class="fa fa-sort columnSortIcons" ng-if="ctrl.reverse"></span>
          <span class="fa fa-sort-down columnSortIcons" ng-if="!(ctrl.reverse)"></span>
          <span class="fa fa-sort-up columnSortIcons" ng-if="ctrl.reverse"></span>
        </th>
      </tr>
      <tr>
        <th ng-repeat="key in getKeysOfCollection(colors[0])">
          <input type="text" ng-model="search[key]" />
        </th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="item in colors | filter:search | orderBy:ctrl.predicate:ctrl.reverse">
        <td ng-repeat="key in getKeysOfCollection(item)">{{item[key]}}</td>
      </tr>

    </tbody>
  </table>

JS代码:

  this.predicate='id';
  this.reverse=false;

  $scope.search = {};

  $scope.colors = [{
    'id': 1,
    'productId': 1001,
    'productName': 'prd 1',
    'minimumLevel': 2,
    'price': 12.50,
    'productDate': '2014-11-01T06:41:30.809Z'
  }, {
    'id': 2,
    'productId': 1002,
    'productName': 'prd 2',
    'minimumLevel': 23,
    'price': 12.54,
    'productDate': '2014-11-02T06:41:30.809Z'
  }, {
    'id': 3,
    'productId': 1003,
    'productName': 'prd 3',
    'minimumLevel': 2,
    'price': 12.50,
    'productDate': '2014-11-04T06:41:30.809Z'
  }, {
    'id': 4,
    'productId': 1004,
    'productName': 'prd 4',
    'minimumLevel': 2,
    'price': 12.50,
    'productDate': '2014-11-22T06:41:30.809Z'
  }, {
    'id': 5,
    'productId': 1005,
    'productName': 'prd 5',
    'minimumLevel': 2,
    'price': 12.50,
    'productDate': '2014-11-18T06:41:30.809Z'
  }];

  $scope.getKeysOfCollection = function(obj) {
    obj = angular.copy(obj);
    if (!obj) {
      return [];
    }
    return Object.keys(obj);
  }

1 个答案:

答案 0 :(得分:1)

ng-if语句中,您不会检查该列是否为已排序列(谓词):

<span class="fa fa-sort-down columnSortIcons" ng-if="!(ctrl.reverse) && key == ctrl.predicate"></span>
<span class="fa fa-sort-up columnSortIcons" ng-if="ctrl.reverse && key == ctrl.predicate"></span>

更新了code