userMod2 userMod2 - 1 year ago 93
AngularJS Question

Angular - When Background/Area outside a div tapped

I've been reading around and can't find an answer to something i would thought be obvious.

I have a menu button that shows/hides a small div pane containing 2 buttons. I'm using

ng-click="main.showLogoutDiv = !main.showLogoutDiv"
to toggle between the 2 states.

However I would also like it if the anywhere outside that div was clicked I can toggle that boolean

Is there something in Angular that lets me check for this?


(btw - i've made my own 'popup pane' - like this screenshot - as I couldn't find anything existing in Angular - have I missed something that comes out the box).

enter image description here

Answer Source

You're looking for the Angular click outside directive by Adam Jowett. You use it on an element like this:

<button id="my-button">Menu Trigger Button</button>
<div ng-controller="MenuController">
    <div class="menu" id="main-menu" click-outside="closeThis()" outside-if-not="my-button">

When a user clicks anywhere outside of that <div>, the closeThis() function in your controller will execute. But if the user clicks on the my-button element, that won't count as a click-outside. This lets you define elements that should be ignored.

Your click-outside function might have code like this:

function MenuController($scope) {
    $scope.closeThis = function () {
        showLogoutDiv = false;

Or you could keep things simpler by not using a scope function and just specifying the showLogoutDiv = false in your HTML using this form:

<div ng-controller="MenuController">
    <div class="menu" id="main-menu" click-outside="showLogoutDiv=false">
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download