I've been searching for a solution to my problem, but haven't found one that meets my criteria of high performance and minimal code.
I have several drop-down menus and I'm looking for a way to toggle their visibility with just one function in JavaScript or JQuery without adding extra attributes to the HTML elements, keeping the DOM lightweight.
Consider these as my buttons (or links in HTML):
<a class="first-menu" href="#">First link</a>
<a class="second-menu" href="#">Second link</a>
<a class="third-menu" href="#">Third link</a>
<div class="first-menu-div">This is first MENU</div>
<div class="second-menu-div">This is Second MENU</div>
<div class="third-menu-div">This is Third MENU</div>
Here's an example using JQuery:
$("a").click(function() {
var class_name = $(this).attr('class');
$("div").hide();
$("." + class_name + '-div').show();
});
Check out the simple JSfiddle demo for this functionality.
Now, I'm curious if there's a way to achieve the same functionality in Angular following Angular's best practices. For instance, we could use the following code:
<a ng-click="showHideMenu('menu1')">Show menu 1 </a>
<a ng-click="showHideMenu('menu2')">Show menu 2 </a>
And here's a possible controller implementation:
$scope.OpenHeaderMenu= function(elementClass){
$(".menus > div").hide();
$(elementClass).show()
//Imagine Angular also offers hide() and show() methods, or a way to dynamically set ng-show and ng-hide based on variables
};
Is it possible to achieve this behavior in Angular like in JQuery, avoiding the use of ng-show
and ng-hide
, and adopting functional programming instead of relying on numerous if | else
statements in the controller for simple menu toggling?
I anticipate having multiple menus on my pages and would prefer a straightforward function call with minimal code for better performance. I hope my inquiry is clear.