AngularJS UI.Router ActiveState implemented with a dropdown menu feature

I am currently working on creating a menu with dropdown functionality for multiple links within my application.

My goal is to have the dropdown menu display as "active" when one of the links below is active.

I have managed to make either the link in the dropdown or the dropdown itself appear as active, but I can't seem to get them both functioning simultaneously. Only one of them works at a time.

If anyone could review the following code and point out where I may be going wrong, it would be greatly appreciated!

<li class="dropdown" ui-sref-active-eq="active">
    <a class="dropdown-toggle" data-toggle="dropdown">
        Main
        <span class="caret"></span>
    </a>

    <ul class="dropdown-menu">
        <li ui-sref-active="active">
            <a ui-sref="Debut1">
                Items
            </a>
        </li>
    </ul>
</li>

EDIT

To see the problem in action, please refer to this Plunker https://plnkr.co/edit/Ffe9FLz4TuihkVjby6RU

ANSWER

app.js

var app = angular.module('app', [
    'ui.router'
]);

app.config([
    '$stateProvider',
    '$urlRouterProvider',
    function ($stateProvider, $urlRouterProvider) {
        var accueil = {
            name: 'accueil',
            url: '/Accueil',
            templateUrl: '/app/views/accueil/accueil.html'
        }

        var debutant = {
            name: 'debut',
            url: '/Debut',
            abstract: true,
            templateUrl: '/app/views/debut/debut.html'
        }

        var debutant1 = {
            name: 'debut.one',
            url: '/One',
            parent: debutant,
            templateUrl: '/app/views/debut/debut1.html'
        }

        var debutant2 = {
            name: 'debut.two',
            url: '/Two',
            parent: debutant,
            templateUrl: '/app/views/debut/debut2.html'
        }

        $stateProvider.state(accueil);
        $stateProvider.state(debutant);
        $stateProvider.state(debutant1);
        $stateProvider.state(debutant2);
        $urlRouterProvider.otherwise('/Accueil');
    }
]);

index.html

<div class="collapse navbar-collapse">
    <ul class="nav navbar-nav">
        <li ui-sref-active="active">
            <a ui-sref="accueil">
                Accueil
            </a>
        </li>

        <li class="dropdown" ui-sref="debut" ui-sref-active="active">
            <a class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
                Début 
                <span class="caret"></span>
            </a>

            <ul class="dropdown-menu">
                <li ui-sref-active="active">
                    <a ui-sref="debut.one">
                        Début 1
                    </a>
                </li>

                <li ui-sref-active="active">
                    <a ui-sref="debut.two">
                        Début 2
                    </a>
                </li>
            </ul>
        </li>
    </ul>
</div>

debut.html

<div ui-view></div>

Answer №1

I finally discovered the true solution to my issue a few days later.

After encountering a console error with @John Spiteri's solution, I decided to make a change:

I updated my code to look like this:

<li class="dropdown" ui-sref-active="{'active': 'debut.**'}">
    <a class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false>
        Début
        <span class="caret"></span>
    </a>

    <ul class="dropdown-menu">
        <li ui-sref-active="active">
            <a ui-sref="debut.one">
                Début 1
            </a>
        </li>
    </ul>
</li>

This change turned out to be the key:

The line in question is: ui-sref-active="{'active': 'debut.**'}"

This configuration matches any child of the parent element!

Answer №2

For all child routes, ui-sref-active will remain active; however, the problem lies in how UI-Router is implemented.

When considering route chaining logically, it can be represented as follows:

'/' = 'app.inventory' //abstract: true - potentially sharing resolve or data
'/inventory/' = 'app.inventory.list'
'/inventory/shoes/' = 'app.inventory.shoes'

To get ui-sref-active to function properly, I had to adjust my approach and mindset accordingly.

By setting the initial (or beginner) route as the parent and then substituting the sole partial with a child, you'll see that the 'accueil' state remains active...

    $stateProvider
      .state('accueil', {
        url: '/accueil',
        views: {
          'content@': {
            templateUrl: './accueil.html'
          }
        }
      })
      .state('accueil.debutant', {
        url: '/debutant',
        views: {
          'content@': {
            templateUrl: './debut.html'
          }
        }
      });
    }

https://plnkr.co/edit/8u3RhHRiPdhdF1lhWbeM?p=preview

I've also included an example where the child remains active...

https://plnkr.co/edit/dXexFM38IUF3uaBGPovL?p=preview

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

`Error: Unresolved reference to Angular service`

I'm encountering an issue in my Ionic/Cordova application where I am trying to implement a loading message using $ionicLoading, but I keep getting the error: ReferenceError: $ionicLoading is not defined Does anyone know how I can successfully pass $ ...

Utilizing event delegation for JavaScript addEventListener across multiple elements

How can I use event delegation with addEventListener on multiple elements? I want to trigger a click event on .node, including dynamically added elements. The code I have tried so far gives different results when clicking on .title, .image, or .subtitle. ...

What prevents me from calling a function while it is being defined in the prototype?

I am experimenting with inheritance through an example. I want to access all properties of objects abc and pqr, so I decided to use Object.create. However, when I try to get the value of r by calling the getr() function, it doesn't seem to work as exp ...

How to invoke a custom JavaScript function within an ejs template

In an ejs file, I included my own JavaScript function which I intended to use within that file. However, the function is not working as it is declared as undefined. Below is how I declared the function inside the ejs file: //my ejs file <script> ...

Implementing Firestore Read Limitations in a React Application

I have encountered an issue with Firebase billing based on the number of document reads. There is a daily limit of 50k reads per day in Firestore, but when I try to fetch documents in my React app, it triggers a quota exceeded error. FirebaseError: Request ...

What happens if I don't associate a function or method in the React class component?

Take a look at this straightforward code snippet that updates a count using two buttons with different values. import "./App.css"; import React, { Component } from "react"; class App extends React.Component { // Initializing state ...

Integration of Angular.js functionalities within a Node.js application

After working on my node.js app for a few weeks, I decided to add some additional features like infinite-scroll. To implement this, I needed to use packages in node.js along with angular.js. So, I decided to introduce angular.js support to the app, specifi ...

Is your Jquery code behaving sporadically, functioning for a moment and then ceasing to

After successfully implementing a slide mechanism on a page, it suddenly stopped functioning properly without any apparent changes being made. Here is the code snippet: $(document).ready(function () { var hash = window.location.hash.substr(1); var ...

Tips for postponing the execution of following tasks until the completion of the setState and ensuring that they are reliant on

I'm encountering an issue with the useEffect hook in my React app that uses useState. Here's the code snippet: const [jobTypes, setJobTypes] = useState([]); const getJobTypes = async () => { try { const response = await fetch(&a ...

The GIF Loader fails to animate while an AJAX request is in progress

Displaying a DIV element containing a loading GIF image while waiting for an AJAX call response. Initially, the DIV element is hidden. Upon clicking a checkbox, the loader DIV is shown, followed by the completion of the AJAX call, and then hiding the load ...

Learning how to use arrow functions with the `subscribe` function in

Can someone help clarify the use of arrow functions in TypeScript with an example from Angular 2's Observable subscribe method? Here's my question: I have code that is functional: this.readdataservice.getPost().subscribe( posts =&g ...

Ways to modify input value based on another input in VueJS

Two sets of text boxes are displayed in a grid format, which can be viewed here. The objective is for users to fill out the top boxes and have the values automatically update as they fill out the corresponding bottom boxes. For example, if you input 100 i ...

Using JQuery to fill an HTML dropdown menu with data from a JSON file

I've been struggling with this issue for a while and despite reading through other posts, I still can't seem to get it to work. My problem lies in populating a drop down menu with JSON data. Although the drop down menu appears on my HTML page, i ...

Troubleshooting a LESS compiling issue with my Jade layout in ExpressJS

Implementing LESS compilation on the server side using Express was successful, but I faced an issue with jade not recognizing less in layout. Error message displayed in my terminal: if(err) throw err; ^ Error: ENOENT, open '/Users/li ...

Can you explain the contrast between onsubmit="submitForm();" and onsubmit="return submitForm();"?

Is it possible that the form below is causing double submissions? <form name="myForm" action="demo_form.asp" onsubmit="submitForm();" method="post"> function submitForm(){ document.myForm.submit(); } I've noticed a bug where sometimes two ...

Provide the email address to use on the forum

Is there a way to code an email address in HTML that will be invisible and undetectable by forums? Thank you in advance. I'm looking for a more advanced solution like this one! <h>mariaburkke76</h><h><h><h><h>< ...

Innovative functionality for adding and deleting elements in JQuery/JavaScript

Is there a way to dynamically add and remove items when the Append/Clear buttons are clicked using this code snippet? $("#btn1").click(function(){ $("ul").prepend("<li>List Item</li>"); }); $("#btn2").click(function(){ $("ul").remove ...

Leveraging Webpack and Jest for seamless module importing in a development project

I've been working on a Node project and utilizing imports and exports extensively. To package the frontend code, I opted for Webpack. However, it seems to require running as common JS. Moreover, Jest is being used in my project, which led me to spec ...

The current status of the ajax call is set to 0

I am currently attempting to retrieve information from a remote server on my local machine. The readyState seems to be fine, equal to 4. However, the status is consistently showing as 0 instead of 200. When I click the button, it doesn't return anythi ...

What is the preferred default value for a property awaiting assignment from a GET response: Undefined or Null?

Say I need to display information about a product, but first I must make a GET request to get the data and assign it to the product. I'm wondering, should the default value for product in the data() function be undefined or null, and is there a differ ...