如何在angularjs中防止/取消绑定之前的$ watch [英] How to prevent/unbind previous $watch in angularjs

查看:296
本文介绍了如何在angularjs中防止/取消绑定之前的$ watch的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在以动态方式使用$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.

推荐答案

在添加新手表之前,您需要检查该手表是否已经存在.如果已经存在,则可以调用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆