最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How to preventunbind previous $watch in angularjs - Stack Overflow

matteradmin5PV0评论

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.

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.

Share Improve this question edited Feb 22, 2017 at 14:54 jediz 4,7175 gold badges41 silver badges42 bronze badges asked May 12, 2015 at 11:21 Ali RazaAli Raza 1,1313 gold badges14 silver badges35 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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;
        }
    });
}
Post a comment

comment list (0)

  1. No comments so far