AngularJS ng-grid with paging sort by all data

I am using an ng grid with swap sorting enabled and client side sorting enabled. When I click on the column heading to sort the data, it works. But it only sorts the data on the current page. I mean, every page is sorted. I want it to sort all the data and display the current page. For example, if I’m on page 2 and sorted by id, it will show me page 1 with the identifiers 5, 7, 10, 11, 12, and when I show the identifiers 1,2,6,8,9 on page 2, although I I want him to show me 1,2,5,6,7 on page 1 and 8,9,10,11,12 on page 2. How can I achieve this?

thanks

+8
angularjs
source share
1 answer

This is how I solved this problem. The basic idea is to manually sort the array containing all your data and paginate again.

define initial sort values

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

Define a function to sort your data in a specific 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 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 sortInfo in your gridOptions

 $scope.gridOptions = { sortInfo: $scope.sortInfo, useExternalSorting: true, } 
+14
source share

All Articles