Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ui.bootstrap pagination - current page not updating/watch not working

I have a pagination inside a dialog both directives are of ui.bootstrap. The problem is that the $watch is not working for currentPage member.

Now, the similar code works perfectly fine for other pages where pagination is not inside some dialog.

I suppose this problem is related to $scope but then currentPage is available in the scope and i can display it on the template using {{currentPage}}

Please find the code in the plunker

$scope.$watch('currentPage') is not firing up on clicking page links.

Now, for the workaround I could use callback on-select-page provided by the pagination directive.

e.g.

<pagination on-select-page="pageChanged(page)" total-items="totalItems" items-per-page = "numPerPage" page="currentPage" max-size="maxSize"></pagination>

and inside my controller i can have,

$scope.pageChanged = function(page) {
  console.log(page);    
};

But I rather need to understand why in such cases $scope.$watch wont work.

Update: From the console following is the watchers value

$$watchers: Array[1] 
0th: Object
  eq: false
  exp: "currentPage"
  fn: function (o,n){}
like image 547
hitesh israni Avatar asked Oct 02 '13 18:10

hitesh israni


2 Answers

Use:

... page="$parent.currentPage" ...

Or proper solution:

When nested scopes are involved bind your vars a level deeper i.e.:

$scope.data.currentPage = ...

details here

example here

like image 169
Max Avatar answered Oct 06 '22 01:10

Max


Because you're creating a new controller (ModalDialogBaseCtl) inside the TestCtrl controller, Angular will create a new scope, which inherits all properties from its parent.

The line that looks suspect to me is where you're assigning a value to $scope.currentPage at the start of ModalDialogBaseCtrl. Angular will interpret this as you declaring a new variable called currentPage in the new scope. However, your pagination control is attached to the currentPage variable in MainCtrl so watching the ModalDialogBaseCtl one does nothing (it never changes value).

One fix is to use $parent as Max suggests, but that is not a great structure. Instead, try to find a way to only have one currentPage property instead of two.

like image 29
kanoop Avatar answered Oct 06 '22 01:10

kanoop