user3632106
user3632106

Reputation: 15

Close dropdown menus on click on other menu item or body (Angularjs)

Can anyone help me? I have various dropdown menus on my application and I'am trying to close them on click on other menu items and on click on body. I'am using angular.js without jQuery.

html

<div ng-controller="SomeController as controller">
<div class="select-box">
    <div class="select-box-field" ng-click="dropdown = !dropdown;">
        <span>Menu Name</span>
    </div>
    <div class="select-box-field-dropdown" ng-class="{ 'is-active':dropdown }">
        <span>Dropdown menu Item 1</span>
        <span>Dropdown menu Item 2</span>
    </div>
</div>

Controller

(function() {

  var app = angular.module('application');

  app.controller('SomeController', someCtrl);

  function someCtrl () { 

    var vm = this;
    vm.dropdown = false;

  };
})();

Here is the fiddle http://jsfiddle.net/aafvxmbn/2/

Upvotes: 1

Views: 9308

Answers (2)

DonJuwe
DonJuwe

Reputation: 4563

Create a directive for your dropdown which also handles the click event. In your case it will just set dropdown = false;. For this, it will bind two event handlers: one on your html and another on the elem itself. Something like this:

myApp.directive('clickOutside', function() {
    return function(scope, elem) {
        var x = document.getElementsByTagName("BODY")[0];
        x.addEventListener('click', function() {
            dropdown = false;
            scope.$apply();            
        });
        elem.addEventListener('click', function(e) {
            e.stopPropagation();
        });
    }
});

It may not work like this, you need to add the directive to your markup and pass dropdown to the directive. Make a fiddle to make it easier to help you.

For more info about detecting outside clicks read How do I detect a click outside an element?

Please see the following fiddle:

Upvotes: 0

Nisham Mahsin
Nisham Mahsin

Reputation: 1399

Update

You can call the same unction from the container and call $event.stopPropagation()

See this updated fiiddle You can set dropdown value in ng-click

<div class="select-box-field" ng-click="change(1)">

or

<div class="select-box-field" ng-click="change(1)">

and in controller the function change()

.controller("Ctrl1", function($scope, $element)
  {
      $scope.dropdown=0;
      $scope.change = function(a) {

            $scope.dropdown=a;
      }

  })

see this fiddle for full working demo

Upvotes: 2

Related Questions