AngularJS dropdown directive hide when clicking outside

This is an old post but in case this helps anyone here is a working example of click outside that doesn't rely on anything but angular.

module('clickOutside', []).directive('clickOutside', function ($document) {

        return {
           restrict: 'A',
           scope: {
               clickOutside: '&'
           },
           link: function (scope, el, attr) {

               $document.on('click', function (e) {
                   if (el !== e.target && !el[0].contains(e.target)) {
                        scope.$apply(function () {
                            scope.$eval(scope.clickOutside);
                        });
                    }
               });
           }
        }

    });

OK I had to call $apply() as the event is happening outside angular world (as per doc).

    element.bind('click', function(event) {
    event.stopPropagation();      
    });

    $document.bind('click', function(){
    scope.isVisible = false;
    scope.$apply();
    });

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

Tags:

Angularjs