How to find which column was sorted and in what order in angular ui.grid. Actually I want to set server based pagination. For this, I what to send data in params as {pageNumber, pageSize, column, order}. Now how to find which column (Name / Age / Number) user has sorted and in what order (ASC / DESC) in angular ui.grid
Asked
Active
Viewed 8,672 times
2 Answers
10
Angular ui-grid launches a sortChanged event when a column has been sorted.
You also must explicitly set useExternalSorting
to true.
You can catch this event in gridOptions in the onRegisterApi
function and handle sort logic in the callback function that takes the grid and the array of sorted columns as parameters like this:
$scope.gridOptions = {
useExternalSorting: true,
columnDefs: [
...
],
onRegisterApi: function( gridApi ) {
$scope.gridApi = gridApi;
$scope.gridApi.core.on.sortChanged( $scope, function(grid, sortColumns){
// sortColumns is an array containing just the column sorted in the grid
var name = sortColumns[0].name; // the name of the first column sorted
var direction = sortColumns[0].sort.direction // the direction of the first column sorted: "desc" or "asc"
// Your logic to do the server sorting
});
}
};

fpavone
- 269
- 3
- 10
1
This can also be done by pushing a div into the cell header as :-
$scope.gridOptions = {
enableSorting: true,
enablePaginationControls: false,
paginationPageSize: 25,
columnDefs: [
{ field: 'name' },
{ field: 'gender',
headerCellTemplate : "<div class='ui-grid-cell-contents has-sort'>"
+ "<a ng-click='grid.appScope.testFunction(\"gender\")'>Gender <i class='fa fa-sort' ></i></a>"
+"</div>"
},
{ field: 'company' }
],
data : [
{
"name": "Ethel Price",
"gender": "female",
"company": "Enersol"
},
{
"name": "Claudine Neal",
"gender": "female",
"company": "Sealoud"
},
{
"name": "Beryl Rice",
"gender": "female",
"company": "Velity"
},
{
"name": "Wilder Gonzales",
"gender": "male",
"company": "Geekko"
},
{
"name": "Georgina Schultz",
"gender": "female",
"company": "Suretech"
},
{
"name": "Carroll Buchanan",
"gender": "male",
"company": "Ecosys"
}
]
};
$scope.testFunction = function(columnName) {
console.log("Sorting..."+columnName);
}
So the headerCellTemplate will push the div into HTML as :-
<div class='ui-grid-cell-contents has-sort'>
<a ng-click='grid.appScope.testFunction('gender')'> Gender <i class='fa fa-sort'></i></a>
</div>
and further you can toggle the order of column in your controller.
Note: You need to add grid.appScope to get the scope of current controller.

Kamaldeep Singh
- 765
- 2
- 8
- 28