2014-10-07 60 views
7

我已經使用ng-table創建了一個應用程序,應用程序工作正常,它使用ng-table生成了表。我面臨的問題是表格排序不起作用。我的代碼如下ng表排序不起作用

Working Demo

HTML

<table ng-table="tableParams" class="table"> 
     <tr ng-repeat="user in myValues"> 
      <td data-title="'Name'" sortable="'name'"> 
       {{user.name}} 
      </td> 
      <td data-title="'Age'" sortable="'age'"> 
       {{user.age}} 
      </td> 
     </tr> 
</table> 

腳本

var app = angular.module('main', ['ngTable']). 
controller('DemoCtrl', function($scope, $filter, ngTableParams) { 
    $scope.myValues = [{name: "Moroni", age: 50}, 
       {name: "Tiancum", age: 43}, 
       {name: "Jacob", age: 27}, 
       {name: "Nephi", age: 29}, 
       {name: "Enos", age: 34}, 
       {name: "Tiancum", age: 43}, 
       {name: "Jacob", age: 27}, 
       {name: "Nephi", age: 29}, 
       {name: "Enos", age: 34}, 
       {name: "Tiancum", age: 43}, 
       {name: "Jacob", age: 27}, 
       {name: "Nephi", age: 29}, 
       {name: "Enos", age: 34}, 
       {name: "Tiancum", age: 43}, 
       {name: "Jacob", age: 27}, 
       {name: "Nephi", age: 29}, 
       {name: "Enos", age: 34}]; 

    $scope.tableParams = new ngTableParams({ 
     sorting: { 
      name: 'asc'  
     } 
    }, { 
     getData: function($defer, params) { 
      $defer.resolve($filter('orderBy')($scope.myValues, params.orderBy())); 
     } 
    }); 
}); 

回答

17
$defer.resolve($filter('orderBy')($scope.myValues, params.orderBy())); 

將創建一個新的有序數組,但不會改變$scope.myValues

$scope.myValues = $filter('orderBy')($scope.myValues, params.orderBy()); 
$defer.resolve($scope.myValues); 

或使用ng-repeat代替myValues$data

<tr ng-repeat="user in $data"> 
+0

感謝戰利品......它的工作!!!!! – 2014-10-07 14:21:14

+0

我認爲使用$ data來獲取項目顯然不是更新數組數據的解決方案。我使用這個,我仍然需要手動過濾到我的getData函數中才能看到我的排序。 thx爲小費 – Alex 2015-11-23 13:05:30

4

給出在HTML,你需要更新myValues爲$的數據。

<tr ng-repeat="user in $data"> 

Plunker

+0

所以如果有兩個表,然後我將如何告訴

因此,要麼,你每次設置$scope.myValues到數組排序哪些數據要採取 – 2014-10-07 14:15:55

+0

感謝您的回答 – 2014-10-07 14:21:32

3

你寫$scope.myValues,並使用在ng-repeat指令 - 但你只能在getData()排序表params對象上的數據。

getData()從來沒有改變$scope.myValues,它只使用它來返回一個排序後的數組。你真正想要做的是:

  • 不要在示波器提供的完整數據集,但其存儲在控制器內的變量:

var data = [{name: "Moroni", age: 50}, ...]

$defer.resolve($filter('orderBy')(data, params.orderBy()));

  • 使用$data裏面的HTML代碼,因爲這是訪問getData()

<tr ng-repeat="user in $data">

+0

感謝您的回答.......... – 2014-10-07 14:21:56