ng-table sorting not working

Alex Man picture Alex Man · Oct 7, 2014 · Viewed 23.6k times · Source

I have created an application using ng-table, the application is working fine which had generated table using ng-table. The problem which i am facing is that the table sorting is not working. My code is as given below

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>

script

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

Answer

manji picture manji · Oct 7, 2014
$defer.resolve($filter('orderBy')($scope.myValues, params.orderBy()));

will create a new sorted array but will not change $scope.myValues.

So either, you set $scope.myValues to the sorted array each time:

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

Or use $data in ng-repeatinstead of myValues:

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