2

I want to use a $timeout in a directive in AngularJS. But I can't find a way in the directive documentation to detect when it is destroyed, in case it happens before my timeout finishes and I need to cleanup the timeout.

Is there an event I can bind to or some built in function (similar to $destroy for controllers) that I can use to detect when my directive will be destroyed? Or am I missing a fundamental concept about directives?

Alex Egli
  • 1,884
  • 2
  • 24
  • 43

1 Answers1

4

The $destroy event you mentioned can also be used in a directive:

app.directive('myDirective', function() {
  return {
    link: function(scope) {
      scope.$on('$destroy', function() {
        // Clean up
      });
    }
  };     
});
Michal Charemza
  • 25,940
  • 14
  • 98
  • 165
  • It's important to notice that the `$destroy` event is related to the scope, not to a controller or a directive. – Blackhole Jan 13 '15 at 21:48
  • Thanks! I completely forgot about directive scope. – Alex Egli Jan 13 '15 at 21:52
  • 1
    @Blackhole I tried to come up with a way that `$destroy` can be triggered with the directive still in the page, or that the directive can be removed from the page without `$destroy` having been triggered. Barring manually tinkering with the DOM, I couldn't think of one. – Michal Charemza Jan 13 '15 at 21:52
  • You're right about that. It was just a comment to help the OP understand what's going on in your code sample ;) . – Blackhole Jan 13 '15 at 22:02
  • Mind you that, if neither your directive nor another directive on the same element requests a new scope (isolated or not), the scope in question will belong to an ancestor of the element, meaning the directive itself might be destroyed and the scope lives on, never notifying your directive about it. – diegovilar May 20 '15 at 15:07
  • @diegovilar Can you give a concrete example, with code, where that happens? – Michal Charemza May 21 '15 at 05:28
  • As others mentioned, using scope for this purpose is not reliable. I think the better approach is shown here: http://stackoverflow.com/a/30778325/1056679. – Slava Fomin II Apr 10 '17 at 15:55