gpt4 book ai didi

javascript - Angular : What is the right way to close dropdown/popover element on outside mouse click?

转载 作者:行者123 更新时间:2023-11-29 10:43:44 25 4
gpt4 key购买 nike

如果我想为应该在此事件后关闭的 popover/tooltip/dropdown 创建指令,我应该在哪里设置外部点击的监听器?

最佳答案

我们为此创建了一个非常简单的指令:

'use strict';

yourmodule.directive('clickOutside', function($parse, $document){
return {
restrict: 'A',
link: function(scope, element, attr) {
var fn = $parse(attr.clickOutside);
$document.bind('click', clickOutsideHandler);
element.bind('remove', function () {
$document.unbind('click', clickOutsideHandler);
});

function clickOutsideHandler(event) {
event.stopPropagation();
var targetParents = $(event.target).parents();
var inside = targetParents.index(element) !== -1;
var on = event.target === element[0];
var outside = !inside && !on;

if (outside) scope.$apply(function() {
fn(scope, {$event:event});
});
}

}
};
});

像这样使用它:

<div click-outside="handleClick($event)">...</div>

关于javascript - Angular : What is the right way to close dropdown/popover element on outside mouse click?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23755765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com