javascript 将事件绑定到 angular 指令中的 $(document)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24363550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:38:33  来源:igfitidea点击:

Binding an event to $(document) inside an angular directive

javascriptjqueryangularjsdocument

提问by Amir Popovich

I have a directive which implements kind of a select box.
Now when the select box is open and I click somewhere outside of it(anywhere else in the document) I need it to collapse.

我有一个指令,它实现了一种选择框。
Now when the select box is open and I click somewhere outside of it(anywhere else in the document) I need it to collapse.

This JQuery code works inside my directive, but I want to do it "the angular way":

这个 JQuery 代码在我的指令中工作,但我想以“角度方式”来做:

  $(document).bind('click', function (e) {
       var $clicked = e.target;
       if (!$clicked.parents().hasClass("myClass")) {
            scope.colapse();
       }
  });

I tried doing thing with injecting the $document service into my directive but didn't succeed.

我尝试将 $document 服务注入到我的指令中,但没有成功。

回答by Yuriy Rozhovetskiy

I believe, the most true Angular way is to use angular.elementinstead of jQueryand accessing window.documentvia the $documentservice:

我相信,最真实的 Angular 方式是使用angular.element而不是通过服务jQuery访问:window.document$document

(function() {

  angular.module('myApp').directive('myDocumentClick', 
    ['$window', '$document', '$log',
    function($window, $document, $log) {
      return {
        restrict: 'A',
        link: function(scope, element, attrs) {
          $document.bind('click', function(event) {
            $log.info(event);
            if (angular.element(event.target).hasClass('myClass')) {
              $window.alert('Foo!');
            }
          })
        }
      };
    }
  ]);

})();

Plunker link

Plunker 链接