Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ng-grid with paging sorting the whole data

Tags:

angularjs

I am using ng-grid with paging and client side sorting enabled. When I click on a column header to get the data sorted, it works. But it sorts only the data on current page. I mean I get each page sorted. I want it to sort all data and display current page. For example if I am at page 2 and sort by id it will show me page 1 with ids 5, 7, 10,11 ,12 and when I to to page 2 it will show me ids 1,2,6,8,9. While I want it to show me 1,2,5,6,7 on page 1 and 8,9,10,11,12 on page2. How can I achieve this?

Thanks

like image 361
Shamaila Tahir Avatar asked Sep 03 '13 06:09

Shamaila Tahir


1 Answers

Here is how I solved this problem. The basic idea is to manually sort the array the contains all your data and the do the pagination again.

define initial sorting values

$scope.sortInfo = {fields: ['id'], directions: ['asc']};

define a function to sort your data on a certain field

// sort over all data
function sortData (field, direction) {
  if (!$scope.allData) return;
  $scope.allData.sort(function (a, b) {
    if (direction == "asc") {
      return a[field] > b[field] ? 1 : -1;
    } else {
      return a[field] > b[field] ? -1 : 1;
    }
  })
}

watch the sortInfo and react to changes

// sort over all data, not only the data on current page
$scope.$watch('sortInfo', function (newVal, oldVal) {
  sortData(newVal.fields[0], newVal.directions[0]);
  $scope.pagingOptions.currentPage = 1;
  setPagingData($scope.pagingOptions.currentPage, $scope.pagingOptions.pageSize)
}, true);

where setPagingData is

// pick the slice we currently want to see
function setPagingData (page, pageSize){
  if (!$scope.allData) return;
  $scope.totalServerItems = $scope.allData.length;
  $scope.myData = $scope.allData.slice((page - 1) * pageSize, page * pageSize);;
};

set the sortInfo in your gridOptions

$scope.gridOptions = {
  sortInfo: $scope.sortInfo,
  useExternalSorting: true,
}
like image 71
dedan Avatar answered Oct 06 '22 01:10

dedan