简体   繁体   中英

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 . 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 .

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?

    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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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