【问题标题】:How to prevent/unbind previous $watch in angularjs如何在angularjs中防止/取消绑定以前的$watch
【发布时间】:2015-05-12 11:21:02
【问题描述】:

我正在以动态方式使用$watch,所以每次调用它都会创建另一个$watch,而我想取消绑定以前的$watch

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

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

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

所以它创建了多个$watch,每次我点击标签时都会创建另一个。

【问题讨论】:

    标签: javascript jquery angularjs angularjs-scope


    【解决方案1】:

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

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

    【讨论】:

    • 很高兴为您提供帮助..谢谢:)
    • $watch返回的函数命名为deregisterer是一个好习惯,因为它是一个在你不再想看时进行清理的函数——它绝对不是观察者
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-01
    • 2013-08-16
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多