i am trying to create a dropdown menu using directives from angularJS and so far it looks like this:
<div class="dropdown">
<button class="button">Dropdown</button>
<ul>
<li><a>Menu Item 1</a></li>
<li><a>Menu Item 2</a></li>
</ul>
</div>
This is the html layout and this is the directive so far:
myApp.directive('dropdown', function($parse) {
return {
restrict: "C",
link: function(scope, elem, attr) {
var isDisabled = $parse(attr.ngDisabled);
var toggleMenu = function() {
if(!elem.hasClass('dropdown-active') && !isDisabled(scope))
elem.addClass('dropdown-active');
else
elem.removeClass('dropdown-active');
};
elem.bind('click', toggleMenu);
}
}
});
So far it works, when i press on the button, the list opens and when i press again it closes but now i have a problem.. i need to make it to close when i press anywhere outside the dropdown.
Can i do that without using jQuery? I am trying to do this project with just AngularJS.
Thank you in advance, Daniel.
Link to Plunker (here i have a problem, when i press on a dropdown, the other one doesnt close)
http://plnkr.co/edit/OrfUVg8KsOhAxqLwn1li?p=preview
I found a way to make this happen, what i did is i use a class 'active-recent' and than just close all the opened menus expect the one that has this class, and just right after, i remove the recent class, so next time when i press on other dropdown, this last one closes aswell.
myApp.directive('dropdown', function($document) {
return {
restrict: "C",
link: function(scope, elem, attr) {
elem.bind('click', function() {
elem.toggleClass('active');
elem.addClass('active-recent');
});
$document.bind('click', function() {
if(!elem.hasClass('active-recent')) {
elem.removeClass('active');
}
elem.removeClass('active-recent');
});
}
}
});
http://plnkr.co/edit/wzJkSb0bU53t7liOoVJZ?p=preview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With