Ng-table sorting doesn't work

I created an application using ng-table, the application works fine, which created a table using ng-table. The problem I am facing is that table sorting is not working. My code is 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())); } }); }); 
+7
javascript sorting angularjs ngtable
source share
3 answers
 $defer.resolve($filter('orderBy')($scope.myValues, params.orderBy())); 

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

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

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

Or use $data in ng-repeat instead of myValues :

 <tr ng-repeat="user in $data"> 
+17
source share

In your HTML you need to update myValues ​​as $ data.

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

Plunker

+4
source share

You write $scope.myValues and use this in the ng-repeat directive, but you only sort the data in getData() in the params object of the table.

getData() never changes $scope.myValues , it uses it only to return a sorted array. What do you really want to do:

  • Do not set the complete data set in scope, but store it in a variable inside the controller:

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

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

  • Use $data inside the HTML code because this is what getData() :

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

+3
source share

All Articles