简体   繁体   中英

How to remove class when pressing anywhere in AngularJS

In the header of the app I'm designing I have 4 buttons like this:

<li ng-click="visible = 1" class="dropdown">
    ....
    <ul ng-class="{'visible': visible==1}" class="dropdown-menu dropdown-messages">
    ....
</li>

I will make the ul visible when user click on an icon (which is the li element). I need to hide the ul when the user press anywhere else in the page.

I tried to set visible=0 on <body ng-click="visible = 0"> but it does not work. How can I set that event?

After long searching I could make this directive

app.directive("outsideClick", ['$document','$parse', function( $document, $parse ){
    return {
        link: function( $scope, $element, $attributes ){
            var scopeExpression = $attributes.outsideClick,
                onDocumentClick = function(event){
                    var isChild = $element[0].contains(event.target);

                    if(!isChild) {
                        $scope.$apply(scopeExpression);
                    }
                };

            $document.on("click", onDocumentClick);

            $element.on('$destroy', function() {
                $document.off("click", onDocumentClick);
            });
        }
    }
}]);

Then just add the outside-click="closeMenu()" in the ul, and

$scope.closeMenu = function(){
    $scope.visible = 0;
}

set the variable to 0, in the controller, to hide the menu dropdown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM