Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS directive $document click event is firing for all instances everytime

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();
          });
      });
    }
like image 695
shaik Avatar asked Dec 14 '22 23:12

shaik


2 Answers

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);
    })
}
like image 55
Arun P Johny Avatar answered Apr 09 '23 20:04

Arun P Johny


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');
      });
  });
}
like image 41
Erik Duindam Avatar answered Apr 09 '23 19:04

Erik Duindam