Creating a dynamic dropdown menu: a step-by-step guide

  <ul class="nav navbar-nav friend-label">
                <li class="dropdown" ng-repeat="module in modules">
                     <a href="" class="dropdown-toggle" data-toggle="dropdown">  
                      {{module.ModuleName}} <b class="caret"></b>
                     </a>

                    <ul class="dropdown-menu">
                        <li  ng-repeat="subModule in module.SubModules">
                            <a href=""><b>{{subModule.SubModuleName}} </b>
                            </a>

                        </li>
                    </ul>
                </li>
   </ul>

I've encountered an issue where a dropdown arrow appears even when there are no submenus present. Clicking the arrow leads to a blank dropdown menu, which is not desired behavior. The Contact Us menu, for example, does not have any submenus but still displays a blank dropdown. I am seeking a solution within the provided HTML code to prevent this unnecessary dropdown from appearing.

Answer №1

By using ngRepeat, you have the ability to dynamically populate menus based on the model:

<span class="dropdown" dropdown on-toggle="toggled(open)">
      <a href class="dropdown-toggle" dropdown-toggle>
        Click here!
      </a>
      <ul class="dropdown-menu">
        <li ng-repeat="choice in items">
          <a ng-click="runFn(choice.fn)">{{choice.name}}</a> 
        </li>
      </ul>
    </span>

To see a comprehensive example, visit Plunker

Answer №2

It seems like your dropdown items are being generated dynamically through ajax or server-side scripting.

If that's the case, you can use some CSS and Javascript to hide empty menus, but there are a few things to keep in mind.

Firstly, ensure that your HTML structure is similar to this:

<li class="dropdown"> 
    <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Contact Us <span class="caret"></span></a>
    <ul class="dropdown-menu" role="menu"></ul>
</li>

Important: Note that there should be no whitespace between the start and end tags of your ul.dropdown-menu. This is necessary for the CSS :empty selector to work correctly.

If there are menu items fetched from a database, they should be placed inside the ul.dropdown-menu as li elements. If it's empty, the dropdown will remain empty with a caret icon visible.

You can use a bit of CSS to hide the empty dropdown:

ul.dropdown-menu:empty {
    display: none;
}

Unfortunately, due to CSS limitations, we can't target the caret directly. So, you may need to utilize a bit of JavaScript/jQuery like this:

$("ul.dropdown-menu:empty").prev("a").children("span.caret").first().hide();

You could implement both solutions using only jQuery if preferred. The presented code snippet gives you an idea of how to handle this situation.

Your setup should now behave similarly to the following example when fully executed. View it in fullscreen mode to prevent any issues.

Example Code Snippet:

$("ul.dropdown-menu:empty").prev("a").children("span.caret").first().hide();
ul.dropdown-menu:empty {
    display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>

<nav class="navbar navbar-default" role="navigation">
    <ul class="nav navbar-nav">
        <li class="active"><a href="#">Home</a></li>
        <li class="dropdown"> 
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Dropdown <span class="caret"></span></a>
            <ul class="dropdown-menu" role="menu">
                <li><a href="#">Action</a></li>
                <li><a href="#">Another action</a></li>
                <li><a href="#">Something else here</a></li>
            </ul>
        </li>
        <li class="dropdown"> 
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Contact Us <span class="caret"></span></a>
            <ul class="dropdown-menu" role="menu"></ul>
        </li>
    </ul>
</nav>

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

What steps can be taken to ensure the Instagram logo remains visible even when it is being hovered over?

Struggling to incorporate a social media icon on my website, I am facing an issue where the Instagram icon outline disappears on hover due to the gradient styling in CSS3. Below is my current code: .social-icons li.instagram a { border-radius: 50%; ...

I am facing an issue with the responsiveness of the mat-card component within a div in

Is it possible to display several small paper cards in a div so that they wrap around the container? ...

NG-model not visible to AngularJS Controller's filter

Finally, the code is working perfectly. It's a mystery to me. I created a custom filter to use with ng-repeat. The code is implemented within a Controller ... .controller('makeOrderController', function ($scope, $timeout, $ionicLoading) { ...

creating a multi-tiered dropdown menu using both CSS and JavaScript

I am in need of a multi-level (drop down) menu feature, that allows me to make changes to the menu in just one file, without having to navigate through each individual page. I require a three level menu. I have attempted to modify someone else's code ...

Example of Image Slider using AngularJS

<body ng-app="myApp"> <div ng-controller="slideShowController" class="imageslide" ng-switch='slideshow' ng-animate="'animate'"> <div class="slider-content" ng-switch-when="1"> <img src="../images/ship.png" /> & ...

Having trouble displaying a local image in CSS using EJS

Hey there, I'm currently working with EJS. In my CSS file, I've added a background image but it's not showing up when the page loads. Strangely, if I use a hosted image, it works perfectly. Here is my directory structure: style.css file: ...

Implementing two background images and dynamically adjusting their transparency

With the challenge of loading two fixed body background-images, both set to cover, I encountered a dilemma. The text on the page was extending below and scrolling, along with top and bottom navigation icons. As expected, the second background covered the f ...

Is there a way to retrieve the controller instance linked to a directive within the link function?

Is there a way to retrieve the controller instance connected with a directive within the link function? return { template: template, controller: controller, controllerAs: 'myCtrl', // What is the method for ac ...

Design a captivating Profile Picture form using HTML and CSS styling

In my form, I am looking to include a user's Profile picture which should be displayed in either a circular or rectangular shape. Initially, the image area will show a black background or a placeholder image. When the user clicks on this area, they sh ...

Adjust the size of the input field as text is being typed in

Can a text input box be automatically resized as text is entered? I've been looking online but haven't come across any solutions. ...

What is the best way to extract all image URLs from a website using JavaScript?

There are various methods to retrieve image src urls using JavaScript, such as utilizing document.images or by targeting all img elements and fetching their src attributes. However, I am currently unable to extract the image urls specified within CSS styl ...

Ways to switch the visibility of a specific thumbnail

Our team has created a new app that showcases all the videos in our channel. Users can browse through thumbnails and click on one to view the related video, instead of viewing all videos at once. Angular Code $scope.isvideoPlaying = false; $scope.displ ...

IItemTransform and minified files that are already in use

Summary: IItemTransform is not triggered when a minified file already exists in the same directory as the original (non-minified) file. Issue Description The problem arises due to CSS relative image references, impacting both JavaScript and CSS files when ...

Chrome behaving differently with CSS for pop-out menu

My issue lies with a pop-out menu behaving differently in Chrome compared to IE or Firefox. Below is the HTML code: <body> <ul> <li><a href="url">Level One</a> <ul> <li><a href="url">Le ...

Looking for browser prefixes for the `text-align` property? We've got you covered! Use `-webkit-right` for Google Chrome and Safari, `-moz-right` for Firefox, and `-o-right` for Opera. But what about

When it comes to browser prefixes or hacks, we often think of: (for Google and Safari) text-align: -webkit-right; (for Firefox) text-align: -moz-right; (for Opera) text-align: -o-right; But what about Internet Explorer? I'v ...

What steps do I need to take to ensure the progress bar extends all the way to the end of the sn

I am currently facing a challenge where the progress bar line in my message queue does not reach the end of the message before it closes. I have included a brief video showcasing the issue along with the relevant code snippet. Any suggestions or ideas woul ...

Looking to populate my HTML fields with values

When attempting to edit, the id is being passed but the data fails to populate in the HTML fields. Please refer to this image. Index @{ ViewBag.Title = "AngularJs Tutorial"; } <style> </style> <h2>AngularJs Tutorial : CRUD operatio ...

What is preventing me from setting a background image in Angular 13?

Trying a different approach based on advice from Stack Overflow, I attempted the following: <div [style.background-image]="'url(https://picsum.photos/200)'"></div> Unfortunately, this resulted in no effect and the image was ...

Unusual ways that backgrounds and borders behave while incorporating CSS transitions for changes in height, positions, and transformations

I was under the impression that I had come up with a brilliant idea... I wanted to create a button with a hover effect where the background would do a wipe transition (top to bottom, left to right) using soft color transitions. My plan was to achieve this ...

Combining ServiceStack with MVC and AngularJs for optimal integration

Setting up web.API with MVC is a breeze - just keep the WebApiConfig.cs as default, create a new web.API controller, and then in your javascript make calls using $http.get("api/..."). I'm interested in achieving the same functionality using service s ...