Search code examples
javascriptjqueryangularjsangularjs-scope

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.


Solution

  • 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;
            }
        });
    }