Javascript 将事件绑定到angular指令内的$(文档)

Javascript 将事件绑定到angular指令内的$(文档),javascript,jquery,angularjs,document,Javascript,Jquery,Angularjs,Document,我有一个实现某种选择框的指令。 现在,当选择框打开,我单击它之外的某个地方(文档中的任何其他地方)时,我需要它折叠 这个JQuery代码在我的指令中工作,但我想“以角度的方式”执行它: 我尝试将$document服务注入到指令中,但没有成功。我认为,最真实的角度方法是使用Angular.element而不是jQuery并通过$document服务访问窗口。document: (function() { angular.module('myApp').directive('myDocumen

我有一个实现某种选择框的指令。
现在,当选择框打开,我单击它之外的某个地方(文档中的任何其他地方)时,我需要它折叠

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


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

我认为,最真实的角度方法是使用
Angular.element
而不是
jQuery
并通过
$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!');
            }
          })
        }
      };
    }
  ]);

})();

能否提供jsifddle/plunker?实际上,当您想使用/操作DOM时,您需要编写指令。因此,我想在指令中附加上述事件处理程序是正确的方法,或者说是有角度的方法来做这些事情。扫描您如何做以及错误是什么?您可以插入带有onclick函数的
$window
。我没有任何问题。我在寻找Yuriy Rozhovetskiy提供的最佳实践解决方案。这正是我所需要的。非常感谢。
(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!');
            }
          })
        }
      };
    }
  ]);

})();