每次都为所有实例触发AngularJS指令$ document click事件

sha*_*aik 4 javascript jquery angularjs angularjs-directive

我想在文档中附加一个事件.单击文档时,我想删除我的指令元素.但它也为所有过去的实例开火.

以下是代码:

link: function(scope, iElement, iAttrs) {
      $document.on('click',function(){
          iElement.slideUp('fast',function(){
              $(this).remove();
          });
      });
    }
Run Code Online (Sandbox Code Playgroud)

Aru*_*hny 8

尝试删除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);
    })
}
Run Code Online (Sandbox Code Playgroud)

  • @EugeneKuzmin抱歉`范围.$ on()` (2认同)