Resetting sorting in ng-grid

Applying sorting to an ng-grid is like a cake walk in Angular JS. But it is little tricky if you want to show the ng-grid with default data (the order in which it loaded first). Here is a solution for it.

Here I am taking a dropdown to change the sort order of the grid. So, I will be using ng-change of the dropdown to update the sort order in ng-grid.

<select ng-change="changeSortOrder" ng-model="empSortCol">
<option>Default Order</option>
<option>Name</option>
<option>Age</option>
<option>Division</option>
</select>

<div ng-grid="myGrid"></div>

Here is the changeSortOrder function.

$scope.changeSortOrder = function() {
      if($scope.empSortCol == 'Default Order') {
           // reset sortInfo 
           $scope.myGrid.ngGrid.config.sortInfo = { columns:[], fields: [''], directions: []};
      }
      else {
           $scope.myGrid.sortBy($scope.empSortCol);      
      }
}

 

If you are using external sorting, you can do it by clearing the lastSortedColumns.

angular.forEach($scope.myGrid.ngGrid.lastSortedColumns, function (c) {
      c.sortPriority = null;
      c.sortDirection = "";
  });
  $scope.myGrid.ngGrid.lastSortedColumns = [];

Leave a Reply

Your email address will not be published. Required fields are marked *