javascript - 如何在angularjs中防止/取消绑定(bind)以前的$watch

标签 javascript jquery angularjs angularjs-scope

我正在以动态方式使用 $watch,因此每次调用都会创建另一个 $watch,而我想解除绑定(bind)之前的 $watch

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

我有多个标签。单击选项卡时,将调用分页函数:

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

因此它会创建多个 $watch 并且每次我单击选项卡时它都会创建另一个。

最佳答案

在添加新 watch 之前,您需要检查观察者是否已经存在。如果它已经存在,您可以调用 watcher() 这将从 $scope.$$watchers 数组中删除观察者。然后注册您的 watch 。这将确保您的 watch 仅创建一次。

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

关于javascript - 如何在angularjs中防止/取消绑定(bind)以前的$watch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30189361/

相关文章:

jquery - 当发生一定量的滚动时隐藏元素

javascript - 如何更改 angularJS+Bootstrap 中的行?

javascript - 我是否正确地履行了这些 promise ?

angularjs - ng-maxlength 搞砸了我的模型

javascript - 在导入的页面行上运行母版页脚本

javascript - 网页 Jquery 下拉按钮不起作用

javascript - 删除 'onKeyUp' 搜索的多个请求

javascript - 如何通过单击按钮将页面中所有文本字段中的数据更改为大写

php - 如何仅在未处理表单时运行某个 Javascript 片段?

javascript: var 仅在 IE 中未定义