chipit24
chipit24

Reputation: 6987

AngularJS trying to hide popup menu when outside area is clicked

I have my HTML set up in the following way:

<div>
    <a href="" ng-click="$scope.show_menu = !$scope.show_menu">Options</a>

    <div class="options_box" ng-show="$scope.show_menu">
        <button>Option1</button>
        ...
    </div>
</div>

And here is my AngularJS code:

myApp.controller('myController', 
    ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {

    $scope.show_menu = false;
    $scope.$window.onclick = function(){
        $scope.show_menu = false;
        $scope.apply();
    };

    ...

} ]);

When the page loads, I receive the following error:

Cannot set property 'onclick' of undefined

If I remove my $window.onclick bit of code, the error disappears and clicking the Options button successfully opens/closes the options popup. What is the correct way to ensure the menu is hidden when any area outside the popup menu is clicked?

Upvotes: 1

Views: 3999

Answers (2)

Hargrovm
Hargrovm

Reputation: 1063

$window isn't a property on the scope. AngularJS $window documentation says $window is a global object. Vaidik is correct in the method to get $window into your controller, so having done that you can write $window.onclick... not $scope.$window.

I'm not sure this is the answer you need though. I would question if it would work if you clicked on a button outside of the menu, as the button would handle the click preventing to event from bubbling up (propagating) to the window...

If you have to click to hide the menu then perhaps you could click on the same button that opened it by toggling ng-show?

Alternatively the menu could just hide when it looses focus i.e. the mouse moves outside the area of the menu - by adding an ng-blur directive to your menu element.

See ngBlur documentation.

Upvotes: 3

vaidik
vaidik

Reputation: 2213

You need to $window like so:

myApp.controller('myController', 
    ['$scope', '$http', '$routeParams', '$window', function($scope, $http, $routeParams, $window) {

    $scope.show_menu = false;
    $scope.$window.onclick = function(){
        $scope.show_menu = false;
        $scope.apply();
    };

    ...

} ]);

Upvotes: 0

Related Questions