最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Detect if directive was removed from DOM - Stack Overflow

programmeradmin1浏览0评论

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?

Share Improve this question asked Jun 11, 2015 at 10:22 alexandernstalexandernst 15.1k25 gold badges107 silver badges213 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

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 plete 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/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);
        });
    };
});
发布评论

评论列表(0)

  1. 暂无评论