How to manually ng-hide something from inside the controller?

http://plnkr.co/edit/ps8TCpQ8znYQnOExO7Er

I have a simple application in which I have an Avatar image and menu. When you click on an avatar image, I use ng-click, ng-classand ng-showanimation show and hide the menu.

HTML:
<div class="avatar"
     ng-click="id_avatar_menu.getMenuClick('clicked menu')"
     ng-class="{ active: avatarMenuBool }">
     <img width="100" height="100" src="http://www.memes.at/faces/are_you_fucking_kidding_me_clean.jpg" title="avatar" alt="user avatar" />
</div>

<div ng-show="avatarMenuBool" id="avatar_menu">
  <ul>
      <li><a href="#">Profile</a></li>
      <li><a href="#">Account</a></li>
      <li><a href="#">Logout</a></li>
  </ul>
</div>

// ANGULAR
// avatar_menu show/hide boolean
$scope.avatarMenuBool = false;

$scope.id_avatar_menu = {};
$scope.id_avatar_menu.getMenuClick = function(val) {
    $scope.avatarMenuBool = !$scope.avatarMenuBool
    console.log(" ");
    console.log(val);
    console.log("$scope.avatarMenuBool = "+$scope.avatarMenuBool);
};

Now it works, clicking the avatar opens and closes the menu. However, I also want the user to be able to click anywhere on bodyor #wrapperand close the menu if the menu is open, but does not close the menu if the user clicks anywhere inside the menu.

I added logic to the controller to determine if the menu is open and if the user clicks inside or outside the menu. I didn't know how to do this in Angular, so using the original Javascript here:

document.getElementById('wrapper').onclick = function(e) {

  console.log(" ");

    if(e.target != document.getElementById('avatar_menu')) {

        console.log('clicked outside');
        if ($scope.avatarMenuBool === true) {
            console.log('code to close open avatar menu here...');
            // $scope.id_avatar_menu.setAttribute("class", "ng-hide-add");
        }

    } else {
        console.log("clicked inside menu... don't close menu");
        // Don't do anything...
    }
}

^ , , , , , . , , .

enter image description here

, Angularians?

+4
1

ng-click body:

<body ng-app="bitAge" ng-controller="AcctCtrl" ng-click="pageClick()">

ng-click , $event:

<div ng-show="avatarMenuBool" id="avatar_menu" ng-click="menuClick($event)">


:

$scope.pageClick = function () {
    $scope.avatarMenuBool = false;
};

$scope.menuClick = function ($event) {
    $event.stopPropagation();  // stop the event from bubbling up any further
};

$event getMenuClick() . . plnkr, , .

http://plnkr.co/edit/borj3btjkMIW9oBBzfL9?p=preview

+4

Source: https://habr.com/ru/post/1570510/


All Articles