Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent/unbind previous $watch in angularjs

I am using $watch in dynamic way so on every call its creating another $watch while I want to unbind previous $watch.

$scope.pagination =function(){
  $scope.$watch('currentPage + numPerPage', function (newValue,oldValue) {      
    $scope.contestList = response; //getting response form $http
  }
}

I have multiple tabs. When a tab is clicked, the pagination function gets called:

$scope.ToggleTab = function(){
    $scope.pagination();
}

so its creating multiple $watch and every time I click on tab it creates another one.

like image 925
naCheex Avatar asked May 12 '15 11:05

naCheex


1 Answers

Before adding a new watch you need to check if the watcher exists already or not. If it's already there you could just call watcher() this will remove the watcher from $scope.$$watchers array. And then register your watch. This will ensure your watch has been created only once.

var paginationWatch;
$scope.pagination = function() {
    if (paginationWatch) //check for watch exists
        paginationWatch(); //this line will destruct watch if its already there
    paginationWatch = $scope.$watch('currentPage + numPerPage', function(newValue, oldValue) {
            //getting response form $http`
            $scope.contestList = response;
        }
    });
}
like image 138
Pankaj Parkar Avatar answered Nov 14 '22 21:11

Pankaj Parkar