Created
December 9, 2013 00:46
-
-
Save ashconnell/7865796 to your computer and use it in GitHub Desktop.
AngularJS Directive for drop-down menus. - Outside clicks close open menus
- Opening another menu, closes all other menu's.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.directive('csDropdown', function($window, $rootScope) { | |
return { | |
restrict: 'A', | |
scope: { | |
bool: '=csDropdown' | |
}, | |
link: function(scope, elem, attrs) { | |
var page = angular.element($window); | |
// On Dropdown Button Pressed | |
elem.on('click', function(e){ | |
e.preventDefault(); | |
e.stopPropagation(); | |
// If closed, open it | |
if(!scope.bool){ | |
open(); | |
// Bind to page click | |
page.on('click', function(e){ | |
var target = angular.element(e.target); | |
// Close menu if the click was outside of the dropdown menu (with clas cs-dropdown-menu) | |
if(!target.hasClass('.cs-dropdown-menu') && target.parents('.cs-dropdown-menu').length == 0){ | |
close(); | |
page.off('click'); | |
} | |
}); | |
// If open, close it | |
} else { | |
close(); | |
page.off('click'); | |
} | |
}); | |
function open(){ | |
$rootScope.$emit('csDropdown:open', {elem: elem}); // Tell other menu's to close | |
scope.$apply(function(){ | |
scope.bool = true; | |
}); | |
} | |
function close(){ | |
scope.$apply(function(){ | |
scope.bool = false; | |
}); | |
} | |
// Close other menu's when another one is opened | |
$rootScope.$on('csDropdown:open', function(e, args){ | |
if(elem != args.elem) close(); | |
}); | |
} | |
}; | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- | |
1. Give the button that opens the menu a cs-dropdown="<boolean-toggle>" | |
2. Give the menu a class cs-dropdown-menu (this is used for checking outside clicks and closing other menus) | |
3. Use <boolean-toggle> in an ng-show, on the element that with be open and closed. | |
--> | |
<div class="dropdown"> | |
<button cs-dropdown="dropdownOneIsOpen">Dropdown One</div> | |
<ul class="options cs-dropdown-menu" ng-show="dropdownOneIsOpen"> | |
<li>Option</li> | |
<li>Option</li> | |
<li>Option</li> | |
<li>Option</li> | |
<li>Option</li> | |
</ul> | |
</div> | |
<div class="dropdown-two"> | |
<button cs-dropdown="dropdownTwoIsOpen">Dropdown Two</div> | |
<ul class="options cs-dropdown-menu" ng-show="dropdownTwoIsOpen"> | |
<li>Option</li> | |
<li>Option</li> | |
<li>Option</li> | |
<li>Option</li> | |
<li>Option</li> | |
</ul> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment