0

I am displaying dropdown menu when I click on an item. It is hiding when I click again on the item. I am trying to hide the dropdown menu if I click anywhere on the window. Here is my code.

<div  ng-click="showDropDown()" class="dropdown">dropDown
                    <div id="myDropdown" class="dropdown-content">
                        <label ng-click="sentToHome()">Home</label>
                        <label  ng-click="sentToContacts()">Contacts</label>
                    </div>
            </div>

Here is my controller:

   $scope.showDropDown = function(){

       document.getElementById("myDropdown").classList.toggle("show"); 
    };

How to close the dropdown if I click anywhere in the page?

1 Answer 1

1

If you wish to close the dropdown when you click outside the select box you can use another custom directive, which listens on the window for click events. This will broadcast a new event which you can listen for:

myApp.directive('dropdownListener', function ($window, $rootScope) {
    return {
        restrict: 'A',

        link: function(scope, element, attr) {
          var w = angular.element($window);

          w.bind('click', function(){
            $rootScope.$broadcast('dropdown:close');
          });
        }
    }
});

This means you can modify the original action by include a listener dropdown:close event:

$scope.$on('dropdown:close', function (event, data) {
   $scope.$apply(function() {
      if($scope.open) { //only close when it is open
        $scope.open = !$scope.open;
      }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.