单击外部时,AngularJS 下拉指令隐藏 [英] AngularJS dropdown directive hide when clicking outside

查看:24
本文介绍了单击外部时,AngularJS 下拉指令隐藏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个带有复选框和过滤器选项的多选下拉列表.我试图通过单击外部来隐藏列表,但无法弄清楚如何.感谢您的帮助.

I'm trying to create a multiselect dropdown list with checkbox and filter option. I'm trying to get the list hidden with I click outside but could not figure it out how. Appreciate your help.

http://plnkr.co/edit/tw0hLz68O8ueWj7uZ78c

推荐答案

注意,您的解决方案(问题中提供的 Plunker)在打开第二个弹出窗口时(在具有多个选择).

Watch out, your solution (the Plunker provided in the question) doesn't close the popups of other boxes when opening a second popup (on a page with multiple selects).

通过点击一个框来打开一个新的弹出窗口,点击事件将始终停止.该事件永远不会到达任何其他打开的弹出窗口(关闭它们).

By clicking on a box to open a new popup the click event will always be stopped. The event will never reach any other opened popup (to close them).

我通过删除 event.stopPropagation(); 行并匹配弹出窗口的所有子元素来解决这个问题.

I solved this by removing the event.stopPropagation(); line and matching all child elements of the popup.

只有当 events 元素与弹出窗口的任何子元素都不匹配时,才会关闭弹出窗口.

The popup will only be closed, if the events element doesn't match any child elements of the popup.

我将指令代码更改为以下内容:

I changed the directive code to the following:

select.html(指令代码)

link: function(scope, element, attr){

    scope.isPopupVisible = false;

    scope.toggleSelect = function(){
        scope.isPopupVisible = !scope.isPopupVisible;
    }

    $(document).bind('click', function(event){
        var isClickedElementChildOfPopup = element
            .find(event.target)
            .length > 0;

        if (isClickedElementChildOfPopup)
            return;

        scope.$apply(function(){
            scope.isPopupVisible = false;
        });
    });
}

我分叉了你的 plunker 并应用了更改:

Plunker:在点击外部时隐藏弹出 div

截图:

这篇关于单击外部时,AngularJS 下拉指令隐藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆