简体   繁体   English

如何从指令元素中删除Angular Watcher?

[英]How to remove angular watcher from directive element?

I have a directive that looks like this: 我有一个看起来像这样的指令:

app.directive('mydirective', function($compile,$document){
    var directive = {
        restrict: 'EA',
        scope:{
        },
        link: link, 
    };  
    return directive; 

    function link(scope, element, attr) {
        var template_html = "<div id=\"popup\">{{popupTitle}}</div>";
        var template = angular.element(template_html);

        element.bind('click', function(){
                if(!$("#popup").is(':visible')){
                    var $popup = $compile(template)(scope);
                    $document.find('body').append($popup);
                }else{
                    $("#popup").remove();
                }
            });

        template.remove();

    }
});

The code works fine showing up and removing the popup element when clicking on mydirective . 单击mydirective时,代码可以很好地显示并删除popup元素。 But, the problem is everytime when the element shows & hide, the angular watcher is just keep on increasing. 但是,问题是每当元素显示和隐藏时,角度观察器就一直在增加。 The number of watcher increase is depending on the number of binding in template_html . 观察者增加的数量取决于template_html中绑定的数量。

How can I get those watcher to be removed when popup is removed so that watchers will not accumulate increase over time. 删除弹出窗口时,如何才能删除那些观察者,以使观察者不会随着时间累积而增加。

Have you tried destroy the scope inside the else block when the popup is being removed? 您是否曾尝试在删除弹出窗口时销毁else块内的作用域?

    element.bind('click', function(){
        if(!$("#popup").is(':visible')){
            var $popup = $compile(template)(scope);
            $document.find('body').append($popup);
        }else{
            $("#popup").remove();
            scope.$destroy();
        }
    });

To create a new scope you could do something like 要创建新的范围,您可以执行以下操作

var popupScope;
element.bind('click', function(){
    if(!$("#popup").is(':visible')){
        popupScope = $scope.$new();
        var $popup = $compile(template)(popupScope);
        $document.find('body').append($popup);
    }else{
        $("#popup").remove();
        popupScope.$destory();
    }
});

Store your watcher in your controller as a variable: watcher作为变量存储在控制器中:

var myWatcher = $scope.$watch(......

And make sure your controller is accessible from your directive, then you can call myWatcher() which will unbind your watcher since calling watch will return an unbound function. 并确保可以从您的指令访问您的控制器,然后可以调用myWatcher()来解除绑定您的观察程序,因为调用watch将返回未绑定的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM