ng-table排序不起作用

时间:2014-10-07 13:39:43

标签: javascript angularjs sorting ngtable

我使用ng-table创建了一个应用程序,应用程序工作正常,使用ng-table生成表。我面临的问题是表排序不起作用。我的代码如下所示

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()));
        }
    });
});

3 个答案:

答案 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)

在HTML中,您需要将myValues更新为$ data。

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

Plunker

答案 2 :(得分:3)

您正在写$scope.myValues,并在ng-repeat指令中使用它 - 但您只需在表params对象的getData()中对数据进行排序。

getData()无法更改$scope.myValues,它只会使用它来返回已排序的数组。你真正想做的是:

  • 不要在作用域上提供完整的数据集,而是将其存储在控制器内的变量中:

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

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

  • 在HTML代码中使用$data,因为这是访问getData()的原因:

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