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, like jQuery).
Is that possible?
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, like jQuery).
Is that possible?
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.
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() {
return function(scope, tElement, attributes) {
scope.$on('$destroy', function() {
alert("In destroy of:" + scope.todo.text);
});
};
});