我使用ng-table创建了一个应用程序,应用程序工作正常,使用ng-table生成表。我面临的问题是表排序不起作用。我的代码如下所示
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()));
}
});
});
答案 0 :(得分:19)
$defer.resolve($filter('orderBy')($scope.myValues, params.orderBy()));
将创建一个新的已排序数组,但不会更改$scope.myValues
。
因此,每次都将$scope.myValues
设置为已排序的数组:
$scope.myValues = $filter('orderBy')($scope.myValues, params.orderBy());
$defer.resolve($scope.myValues);
或者使用$data
中的ng-repeat
代替myValues
:
<tr ng-repeat="user in $data">
答案 1 :(得分:4)
答案 2 :(得分:3)
您正在写$scope.myValues
,并在ng-repeat
指令中使用它 - 但您只需在表params对象的getData()
中对数据进行排序。
getData()
无法更改$scope.myValues
,它只会使用它来返回已排序的数组。你真正想做的是:
var data = [{name: "Moroni", age: 50}, ...]
$defer.resolve($filter('orderBy')(data, params.orderBy()));
$data
,因为这是访问getData()
的原因: <tr ng-repeat="user in $data">