Ways to toggle elements in AngularJS using a function that takes in the element class as a parameter similar to JQuery techniques

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.

Answer №1

It seems your approach may not be the most effective as modifying DOM objects directly from a controller is generally discouraged. Instead, consider utilizing ng-show, ng-hide, and $scope in combination to update your view seamlessly.

An alternative implementation could look like this:

$scope.handleClick = function(showItem) {
    $scope.showItem = showItem;
};

In your HTML view:

<a ng-click="handleClick(true)">Show Menu 1</a>

<div ng-show="showItem">
Some item
</div>

Instead of manipulating elements directly within your controller, it's recommended to create a directive for this purpose. However, that's a different topic altogether.

I found a JSFiddle demo that might be helpful for what you're trying to achieve.

Hope this explanation clarifies things for you.

Edit: Simply pass a variable to ng-show with an expression to display elements based on specific conditions.

$scope.toggleMenu = function(item) {
    $scope.menuClass = item;
}

<a class="first-menu" ng-click="toggleMenu(1)" href="#">First Link</a>
<a class="second-menu" ng-click="toggleMenu(2)" href="#">Second Link</a>
<a class="third-menu" ng-click="toggleMenu(3)" href="#">Third Link</a>

<div class="first-menu-div" ng-show="menuClass == 1">
    This is the First Menu
</div>
<div class="second-menu-div" ng-show="menuClass == 2">
    This is the Second Menu
</div>
<div class="third-menu-div" ng-show="menuClass == 3">
    This is the Third Menu
</div>

Feel free to check out my JSFiddle example.

Answer №2

To implement ngshow without using any classes or selectors, you can refer to the code snippet below:

(function () {
  'use strict';

  angular
    .module('testApp', [])
    .controller('HeaderCtrl', function () {
      this.target =false;
  });


}());
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="testApp">
    <div ng-controller="HeaderCtrl as hd">
      <a href="#" ng-click="hd.target= 'first'">First link</a>
      <a href="#" ng-click="hd.target= 'second'">Second link</a>
      <a href="#" ng-click="hd.target= 'third'">Third link</a>


      <div ng-show="hd.target == 'first'">
        This is first MENU
      </div>
      <div ng-show="hd.target == 'second'">
        This is Second MENU
      </div>
      <div ng-show="hd.target == 'third'">
        This is Third MENU
      </div>

    </div>
  </div>

Answer №3

One potential solution for your issue could be utilizing ng-switch along with ng-switch-when.

$scope.selectTab = function(tabNumber){
  $scope.activeTab = tabNumber;
}

Within your HTML view, you can implement the following:

<a ng-click="selectTab(1)">Display Tab 1 </a>
<a ng-click="selectTab(2)">Display Tab 2 </a>

<ANY ng-switch="activeTab">
  <ANY ng-switch-when="1">...</ANY>
  <ANY ng-switch-when="2">...</ANY>
  <ANY ng-switch-default>...</ANY>
</ANY>

You have the option to customize the initial section of the view, this is just a hardcoded example provided for demonstration purposes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combining Data from Header to Body using HTML5 and JavaScript

I am struggling to figure out how to transfer variables declared in the script from the header of my code to the body. Specifically, I want to capture the user input in the script and replace a placeholder in the body. Here is an example of what I am tryin ...

Generating a sequential array of dates and times in Angular

Currently, I am working on implementing a feature that will allow users to see the available visit times between two dates they select, specifically from 8:00 to 17:00 every day. For instance: If a user selects 1 Sep to 4 Sep, the system should return [1. ...

What is the simplest way to display an HTTP response in an alert window?

Struggling to display the JSON response using JavaScript's window.alert or alert. As a non-native JS coder, I apologize for my lack of experience. Here are a few attempts I've made based on online examples. My objective is to showcase the JSON r ...

Can you explain the differentiating factors of a document and the DOM?

I recently read an article discussing the distinction between jQuery's bind() and live() functions. You can check it out here: http://msdn.microsoft.com/en-gb/scriptjunkie/ee730275.aspx (specifically the Live and Let Die section). The bind function ...

Inserting items into arrays in Angular

I've encountered an issue with pushing an object into an array. The array contains objects, and this component is responsible for displaying them: <div class="row" *ngFor="let element of dietList"> {{element.name}} {{ element.weight }} </d ...

Set a Minimum Browser Size Requirement for Your Website

As a web designer, I incorporate numerous absolute elements into my website layout to ensure it adjusts seamlessly to various browser dimensions. However, I do have a minimum size in mind that I want to maintain. Essentially, I aim for my website to remain ...

jQuery is throwing an error stating that there is a missing ) after the argument list. However, even though the parentheses are closed and quotes are

I can't figure out why I keep getting the error message missing ) after argument list when working with this jQuery code. I made sure all the parentheses are properly closed and even tried escaping the quotes, but it's still not working. $(" ...

Utilize VueJS to streamline your filtering process

I recently started learning VueJS and I am facing an issue with using the vue filter. I need help resolving this problem. Below is a snippet of my HTML file. However, when I attempt to use this code, the items in v-for are not being displayed and there i ...

What are the steps to secure an API endpoint using PassportJS?

Within my app, I have integrated Express and AngularJS for functionality. Specifically, I am utilizing express to manage the basic web serving of the angular code through static routes. The angular code interacts with services that connect to API endpoin ...

Is it possible to change the background color of a MUI theme in ReactJS by using Css

Currently, I am utilizing Material UI to create a theme that is functioning correctly. However, upon adding <CssBaseline/> to the App.js file, it unexpectedly changes the background color to white instead of the intended #1f262a specified in the inde ...

Create a new tab that is active and use ng-repeat in the uib-tab directive

I've been trying to solve this problem for a while now. I came across a similar post, but it was left unanswered. So, I decided to create my own post with a Plunkr example. The issue I'm facing is that upon loading, the ui-tab always defaults to ...

How can I use str.match to strip out the "$" symbol and display only the numerical value?

Check out this code snippet: value = str.match(/$(\d+)/); Take for instance, Example 1: HK$999 Result to Display = 999 Consider Example 2: HK$1,999.20 Displayed result = 1 (not the desired outcome) How can I show Example 2 as 1999? Thank you every ...

Adding HTML content to a DOM element using Angular

Looking to create a directive that can dynamically append HTML content within a div element. Specifically, I need this directive to handle HTML data fetched from the server using an $http post request. <div id="invoice_template_preview" ng-bind-h ...

Cypress fails to log requests in the Command Log

I'm having trouble intercepting requests to the Backend using Cypress. Strangely, I can't see some of the XHR requests in the DevTools, even though they are there. To help illustrate the issue, I've included a screenshot with arrows. https:/ ...

Discover the steps to handle parameters received in a $resource GET request

When working in the controller: MyService.get({queryParameter:'MyQueryParameter'}).$promise.then(function(result){ return result; }; Within my service, I include: $resource('/api/path',{ queryParameter: (function manipulate(quer ...

Displaying data in table rows using ng-repeat

I'm trying to organize the table data in a specific way, similar to the example shown below. I've managed to display the years at the top and the list of companies down the first column. However, I'm struggling with how to include the yield ...

Create a new NVD3 graph with a vertical line added

I am working with a NVD3 graph that displays a simple data set. My goal is to draw a line over the graph in a different color (similar to a cut-off value, which will be at x=5) <meta http-equiv="content-type" content="text/html; charset=UTF8"> <s ...

The HTML5 webpage is failing to send a JQuery Ajax request

I am encountering an issue with my Ajax setup on a HTML page. The call to a web service does not seem to be working as intended, and I suspect that the ajax call is not even reaching the web service at all. The problem arises when I click the button, an e ...

Troubleshooting Media Queries in HTML, CSS, Bootstrap: Why Aren't They Applying as Expected?

I am still fairly new to web programming and just starting out with bootstrap. After creating a section of my page that worked well on larger screens, I realized it wasn't responsive enough on smaller devices. The height was set at 400px, causing hor ...

Initiate a function following a 3-second click on an image

I'm facing a peculiar challenge with my website - I have an invisible button that needs to be pressed for 3 seconds in order to trigger a specific action. Here is what I've attempted so far: $("#basicChn").on({ mousedown: function() { $ ...