Detect if directive was removed from DOM

删除回忆录丶 提交于 2019-12-11 09:27:32

问题


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?


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




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


来源:https://stackoverflow.com/questions/30778150/detect-if-directive-was-removed-from-dom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!