How to implement pagination in ng-grid?
How-to
Here has code snippet:
1. enable pagination function, and set pagingOptions & totalServerItems in ng-grid
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | $scope.gridCols = [ { field : 'no', displayName : '序號', width : '5%', cellClass : 'text-right' }, { field : 'exceptionGroup', displayName : '異常類別', width : '15%', cellClass : 'text-left' }, { field : 'exceptionDesc', displayName : '異常類別說明', width : '25%', cellClass : 'text-left' }, { field : 'deptName', displayName : '部門別', width : '15%', cellClass : 'text-left' }, { field : 'userName', displayName : '通報人員姓名', width : '10%', cellClass : 'text-left' }, { field : 'emailAddr', displayName : '收件Email', width : '30%', cellClass : 'text-left' } ]; $scope.dataGrid = { multiSelect : false, data : 'itemData', columnDefs : 'gridCols', enableColumnResize : true, keepLastSelected : false, enablePaging : true, showFooter : true, pagingOptions : $scope.pagingOptions, totalServerItems : "totalServerItems" }; |
2. set initial values when page loaded
1 2 3 4 5 6 7 8 9 10 11 12 13 | // query result (current page) $scope.itemData = []; // query result (complete data) $scope.resultData = []; // set page sizes, page size and current page $scope.pagingOptions = { pageSizes : [ 25, 50, 100 ], pageSize : 25, currentPage : 1 }; // total items are on the server (initial value) $scope.totalServerItems = 0; |
3. set data to current page
1 2 3 4 5 6 7 8 9 | // set paging data $scope.setPagingData = function(data, page, pageSize) { var pagedData = data.slice((page - 1) * pageSize, page * pageSize); $scope.itemData = pagedData; $scope.totalServerItems = data.length; if (!$scope.$$phase) { $scope.$apply(); } }; |
4. Registers a listener callback to be executed whenever the pagingOptions changes.
1 2 3 4 5 6 7 8 9 10 11 12 13 | // Registers a listener callback to be executed whenever the pagingOptions changes. $scope.$watch('pagingOptions', function(newVal, oldVal) { // if page size change, then set current page to 1 and set paging data if(newVal.pageSize !== oldVal.pageSize) { $scope.pagingOptions.currentPage = 1; $scope.setPagingData($scope.resultData, $scope.pagingOptions.currentPage, newVal.pageSize); } // if current page change, then set paging data if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) { $scope.setPagingData($scope.resultData, newVal.currentPage, newVal.pageSize); } }, true); |
Screenshot is as bellows:
Reference
[1] https://angular-ui.github.io/ui-grid/
No comments:
Post a Comment