如何在 angularjs 中防止/解除绑定先前的 $watch [英] How to prevent/unbind previous $watch in angularjs
问题描述
我以动态方式使用 $watch
,所以每次调用它都会创建另一个 $watch
,而我想取消绑定以前的 $watch
.
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();
}
所以它创建了多个 $watch
并且每次我点击标签时它都会创建另一个.
so its creating multiple $watch
and every time I click on tab it creates another one.
推荐答案
在添加新 watch 之前,您需要检查 watcher 是否已经存在.如果它已经存在,您可以调用 watcher()
这将从 $scope.$$watchers
数组中删除观察者.然后注册您的手表.这将确保您的手表仅创建一次.
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;
}
});
}
这篇关于如何在 angularjs 中防止/解除绑定先前的 $watch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!