Skip to content Skip to sidebar Skip to footer

Detect If Directive Was Removed From Dom

I have an AngularJS directive and I need to perform certain actions if the directive's element is removed from the DOM (either from inside an AngularJS call or by any other method,

Solution 1:

In the directive, when an element is removed from DOM, $destroy event is emitted. Inside your directive's link function, you can do this:-

element.on('$destroy', function() {
   // do stuff
});

For more information and complete example, see documentation here

EDIT: See this plunker to see $destroy in action. Here, I am removing the element after 2 seconds, and logging destroyed in console.

Solution 2:

When your directive is removed from the DOM, an $destroy event is fired. See here https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$destroy

In this question (Provide an example of scope's $destroy event?) I found the following example:

ctrl.directive('handleDestroy', function() {
    returnfunction(scope, tElement, attributes) {        
        scope.$on('$destroy', function() {
            alert("In destroy of:" + scope.todo.text);
        });
    };
});

Post a Comment for "Detect If Directive Was Removed From Dom"