AngularJS dropdown directive hide when clicking outside

后端 未结 9 2107
长发绾君心
长发绾君心 2020-11-29 22:06

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. A

9条回答
  •  Happy的楠姐
    2020-11-29 22:42

    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).

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

    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 (directive code)

    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;
            });
        });
    }
    

    I forked your plunker and applied the changes:

    Plunker: Hide popup div on click outside

    Screenshot:

    Plunker Screenshot

提交回复
热议问题