How to find which column was sorted and in what order in angular ui.grid

Kamaldeep Singh picture Kamaldeep Singh · Sep 23, 2015 · Viewed 8.2k times · Source

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

Answer

fpavone picture fpavone · Sep 23, 2015

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