Niranjan Godbole
Niranjan Godbole

Reputation: 2175

How to close dynamically generated dropdown on clicking on the body using angularjs?

Hi i am developing web application in angularjs. On top right corner i have one drop-down box and this will become active only after user logged in. I have scenario where user clicks on dropdown and once he clicks anywhere on the page i want to close the dropdown. I am struggling to fix this from long time. I have created plunker in order to understand what problem i am facing properly.

`https://plnkr.co/edit/4RjrBDHE6mmxofwRovfB?p=preview`

May i get some help here to fix this? Any help would be greatly appreciated!. Thank you...

Upvotes: 1

Views: 170

Answers (1)

Vivz
Vivz

Reputation: 6620

You can use $event.stopPropagation. You can add the following code to make it work

HTML:

<div class="user" ng-click="OpenDropdown($event)">
   <h1>Dropdown</h1>
   <div class="user-dropdown" ng-show="dp" id="ProfileDropdown"></div>
</div>

JS:

$scope.OpenDropdown = function(event) {
    if ($scope.dp === false || $scope.dp === undefined) {
        $scope.dp = true;
        event.stopPropagation();
    } else {
        $scope.dp = false;
    }
};
window.onclick = function() {
    if ($scope.dp) {
        $scope.dp = false;
        $scope.$apply();
    }
};

Working Demo: https://plnkr.co/edit/6h91NXc4S8zD7jAbOz33?p=preview

If you want to use a directive to achieve this, check out this solution

Upvotes: 1

Related Questions