Ali Raza
Ali Raza

Reputation: 1131

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.

Upvotes: 5

Views: 1756

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

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

Upvotes: 8

Related Questions