Currently, I am in the process of developing a directive to manage a side menu within a mobile application. The menu opens smoothly with the directive I've implemented, but I am facing a challenge in selecting everything except the menu using jqLite. This is necessary so that I can associate a click event to close the menu if any area outside the menu is clicked.
Here is the code snippet of my current directive:
.directive('asideMenuButton', [function() {
return {
restrict: 'A',
link: function(scope, $el, attrs) {
$el.on('click', function(e) {
e.preventDefault();
var $aside = angular.element(document.getElementById(attrs.parent));
if ($aside.hasClass('active')) {
$aside.removeClass('active');
} else {
$aside.addClass('active');
}
});
}
};
}]);
The usage of the directive is as follows:
<a aside-menu-button href="#" data-parent="<aside ID>">Link</a>
Is there a way to utilize jqLite to target any element except the menu?
Edit: Here is the final solution I implemented:
angular.module('wowpr.directives', [])
.directive('asideMenuButton', [function() {
return {
restrict: 'A',
link: function(scope, $el, attrs) {
var $aside = angular.element(document.getElementById(attrs.parent));
var $body = angular.element(document.getElementsByTagName('body'));
$body.on('click', function(e) {
if ($aside.hasClass('active')) {
$aside.removeClass('active');
}
});
$aside.on('click', function(e) {
e.stopPropagation();
});
$el.on('click', function(e) {
e.preventDefault();
e.stopPropagation();
if ($aside.hasClass('active')) {
$aside.removeClass('active');
} else {
$aside.addClass('active');
}
});
}
};
}]);
In this solution, the body click event does not check if the clicked element is the menu. Instead, by clicking on the menu, the propagation of the click event to the body is halted. This prevents the firing of the body click event when the menu is clicked.