绑定事件的$(document)的角度指令内 [英] Binding an event to $(document) inside an angular directive
本文介绍了绑定事件的$(document)的角度指令内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一种实现选择框的指令。
现在,当选择框是开放的,我(在文件中其他地方)点击某处它外面我需要它崩溃。
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.
这JQuery的code我的作品里面的指令,但我想这样做角路:
This JQuery code works inside my directive, but I want to do it "the angular way":
$(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.
推荐答案
我相信,最真实的角度的方法是使用 angular.element
而不是的jQuery
和访问 window.document
通过 $文件
服务:
I believe, the most true Angular way is to use angular.element
instead of jQuery
and accessing window.document
via the $document
service:
(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!');
}
})
}
};
}
]);
})();
这篇关于绑定事件的$(document)的角度指令内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文