4

I want to attach an event to the document. when document is clicked I want to remove my directive element. but it is firing for all past instances also.

Below is the code:

link: function(scope, iElement, iAttrs) {
      $document.on('click',function(){
          iElement.slideUp('fast',function(){
              $(this).remove();
          });
      });
    }
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
shaik
  • 275
  • 2
  • 6
  • 11

2 Answers2

8

Try to remove the handler in the destroy handelr

link: function (scope, iElement, iAttrs) {
    function handler() {
        iElement.slideUp('fast', function () {
            $(this).remove();
        });
    }

    $document.on('click', handler);
    scope.$on('$destroy', function () {
        $document.off('click', handler);
    })
}
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
4

When you add jQuery events like this, the event will stay alive even after the directive is destroyed. You have to specifically turn the event off like this:

link: function(scope, iElement, iAttrs) {
  $document.on('click',function(){
      iElement.slideUp('fast',function(){
          $(this).remove();
          $document.off('click');
      });
  });
}
Erik Duindam
  • 349
  • 1
  • 8