2014-07-17 148 views
2

我有一個簡單的表格,可以在單擊列時按照升序/降序對列進行排序。但是,我希望每列都能「記住」它是以前的狀態,並在點擊時做相反的操作。例如,如果我第一次點擊列名name,它將按順序排序。然後假設我點擊不同的列,並按該asc排序。然後我再次點擊namename應按降序排列。以asc/desc順序訂購表格列

但是,我正在使用的方法不存儲其中列,即使我做了,我也無法在代碼的排序部分訪問它。我在列上不使用ng-repeat,所以我不確定如何繼續。箭頭正常工作(除了您應該一次只排序1個,因此只能看到1個),但是如何訪問行重複部分中的列名?有任何想法嗎?

這裏是一個JSFiddle:

代碼:

 <script> 
    var app = angular.module('app', []); 
    app.controller('ctrl', ['$scope', 

    function($scope) { 
     $scope.data = tastyJSON; 

     $scope.columns = Object.keys($scope.data[0]); 

     $scope.order = {}; 

     $scope.sort = function(column){ 
      console.log(angular.toJson($scope.order)); 
     if ($scope.order[column] == column) { 
      $scope.order[column+'Desc'] = !$scope.order[column+'Desc']; 
     } else { 
      $scope.order[column] = column; 
      $scope.order[column+'Desc'] = false; 
     } 
     }; 

    }]); 
</script> 
<div ng-app="app" ng-controller="ctrl"> 
    <table> 
     <tr> 
      <th ng-repeat="column in columns" ng-click="sort(column)"> 
       <a href="">{{column}}</a> 
       <a ng-show="order[column] == column && order[column+'Desc']">v</a> 
       <a ng-show="order[column] == column && !order[column+'Desc']">^</a> 
      </th> 
     </tr> 
     <tr ng-repeat="row in data | orderBy:order[column]: order[column+'Desc']"> 
      <td ng-repeat="column in columns"> 
       {{row[column]}} 

      </td> 
     </tr> 

    </table> 
</div> 

回答

3

你非常接近!你唯一缺少的是跟蹤當前的排序。這裏是我的變化:

$scope.sort = function(column){ 
    if ($scope.order[column] == column) { 
    $scope.order[column+'Desc'] = !$scope.order[column+'Desc']; 
    } else { 
    $scope.order[column] = column; 
    $scope.order[column+'Desc'] = false; 
    } 

    $scope.currentSort = {exp: $scope.order[column], reverse: $scope.order[column+'Desc']} ; 
}; 

查看代碼:

<a ng-show="currentSort.exp == column && currentSort.reverse">v</a> 
<a ng-show="currentSort.exp == column && !currentSort.reverse">^</a> 

...

<tr ng-repeat="row in data | orderBy:currentSort.exp: currentSort.reverse"> 

Updated Fiddle.

+0

早該知道!它非常簡單。謝謝。 –