Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS dropdown directive hide when clicking outside

Tags:

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

like image 652
Amitava Avatar asked Jan 29 '13 01:01

Amitava


People also ask

Which directive is used to hide a given control?

B - ng-hide directive can hide a given control.

What is Ng click?

ng-click is an attribute of an HTML element that can be used for the customized components in Angular. We use this attribute to detect if an element is clicked and tracks the mouse's cursor. ng-click takes a function as an attribute and calls it whenever an element is clicked.


1 Answers

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

like image 159
cheneym Avatar answered Sep 20 '22 22:09

cheneym