Why is this ng-grid pagination working

1k views Asked by At

Here is what I understand by the if condition in the following code:

$scope.pagingOptions = {
    pageSizes: [250, 500, 1000],
    pageSize: 250,
    currentPage: 1
};

$scope.$watch('pagingOptions', function (newVal, oldVal) {
    if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
          $scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
    }
}, true);

whenever the pagingOptions changes and the currentPage property has changed the if conditions becomes true, so the getPagedDataAsync method gets executed.

But even if I don't change the currentPage but the pageSize from the UI, the grid gets refreshed. Which I don't expect to happen(according to my understanding). So why is that grid getting refreshed?

From here, I have taken the code:

http://angular-ui.github.io/ng-grid/ with the Server-Side Paging Example heading

3

There are 3 answers

2
Davin Tryon On

The true at the end of the $watch indicates a deep watch of the scope object pagingOptions.

So, if true is passed in as on optional third parameter, Angular will do a deep equality check. Therefore, the pageSize property will be checked for equality and will be different.

Documentation for $watch and the third parameter [objectEquality] is here.

0
hon2a On

The provided code seems to contain unnecessary complexity. When doing an "object equality watch" (by setting the third argument of $watch to true), object's property values are compared instead of object reference. If we suppose that pageSizes property value never changes, the watch informs us properly and only about changes to pageSize and currentPage values. So the only code needed inside is the call to page refresh:

$scope.$watch('pagingOptions', function () {
      $scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
}, true);
0
AudioBubble On

Add one more watch

$scope.$watch('pagingOptions.pageSize', function (newVal, oldVal) {
 if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) {
      $scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage, $scope.filterOptions.filterText);
    }
}, true);