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

My toggleclass function seems to be malfunctioning

I am encountering a strange issue with my jQuery script. It seems to work initially when I toggle between classes, but then requires an extra click every time I want to repeat the process. The classes switch as expected at first, but subsequent toggles req ...

Issue with jQuery's outerHeight() function persisting despite attempting to fix it with jQuery(window).load()

Once the content is loaded using AJAX, I need to retrieve the outerHeight of the loaded elements. Ajaxload file: $('#workshop').submit(function(event){ $.ajax({ url: URL, type: 'POST', data: $(' ...

Attempting to find a solution to successfully transfer an object from the jEditable datatable plugin to my Java Servlet

Currently, I have a Datatable set up and I am utilizing the jeditable plugin to make cells editable and update data. However, after editing a cell and hitting enter, when the data is sent back to my URL Rest endpoint (where I simply have a System.out.print ...

Using JQuery to find the nearest element and narrowing down the search to its child elements

In my program, I have 3 forms identified by form1, form2, and form3. Each form contains its own set of dropdown lists named drop1 and drop2, along with a submit button. When the submit button is clicked in any form, it checks which option was selected from ...

Iterate through a JavaScript grid and display the items

I am attempting to iterate through a JavaScript table, aiming to display the elements located between two selections made by the user. Here is an example of the table structure: if the user selects IDs 2 and 5, the loop should display rows 3 and 4. I trie ...

What is the best way to determine the total number of rows that have been generated by the Asp:Repeater?

I'm looking for a way to retrieve the total number of rows generated by the repeater control using either Javascript or JQuery. Can anyone help me with this? ...

Tips for retrieving specific database entries using a JavaScript function

I'm currently in the process of developing a web directory that showcases organizations based on the selected county by utilizing an XML database. During testing, I have configured it to only display organization names and counties for now. However, ...

Angular8 Chart.js customizes the Y axis tick labels

Is there a way to dynamically adjust the Y-axis ticks in a chart.js graph? I attempted to modify them using the following commands: this.chartOptions.scales.yAxes[0].ticks.min = 10; this.chartOptions.scales.yAxes[0].ticks.max = 18; ...

Using Node.js: Interacting with npm inside a module

Is there a more efficient way to implement self-updating functionality for a globally installed module than using the code snippet below? require("child_process").exec("npm update -g module-name"); I came across some documentation regarding installing np ...

Exploring a section of a react-chartjs Pie chart

I'm currently exploring how to create a static Pie chart using react-chartjs-2. Wanting to make one slice stand out more than the others, I aim to have it appear larger: My focus is on accessing a specific slice in the pie chart and adjusting its out ...

Gain a comprehensive understanding of the JavaScript syntax utilized throughout the code

I stumbled upon this JavaScript code that enables asynchronous file uploads, but there are certain parts of it that I'm struggling to grasp. Any insights or explanations would be greatly appreciated - many thanks in advance. // Utilizing Ajax for Fil ...

`The node API is encountering an error when attempting to `post` data due to the body parameter being read as labels. How can this

When I post data to the back-end using Postman, everything works fine. However, when I try to post the data through Angular using the same API, I encounter an issue. It seems that there is a problem with my form data in the POST process that I can't s ...

Issue with Angular JS: ng-repeat not refreshing within ng-view

Whenever I make changes to the data stored in the variable $scope.userMovies, ng-repeat fails to update when it is inside an ng-view. Strangely enough, if it's placed outside of ng-view, everything updates as intended. What could be the reason behind ...

How can I force an element to overflow without being affected by its parent's overflow style in CSS/HTML/JS, even if the parent is

I've come across many inquiries on this subject, but the proposed solutions never seem to work when dealing with ancestors that have absolute positioning. Take this example: <div id='page'> <div id='container' style= ...

Emptying the trumbowyg editor within an Angular environment

I am currently experiencing issues with the trumbowyg editor in a project I'm working on. I am able to update the editor by changing its model but cannot seem to clear its content using $scope.editorModel = '';. For a more detailed explanati ...

Refreshing the page causes Material UI Button to revert to default styling

My question regarding the Material UI Button losing styling after a page refresh (link: Material UI Button loses Styling after page refresh) went unanswered, so I am reposting with a CodeSandbox included for reference: https://codesandbox.io/s/bold-resonan ...

Trigger a notification based on the selected choice

Here is some sample HTML code: <div id="hiddenDiv" style="display: none;"> <h1 id="welcomehowareyou">How are you feeling today?</h1> <select name="mood" id="mood"> <option value="" disabled selected>How are you feeling?</o ...

Javascript detecting key press event only firing once when a key is continuously held down

I have implemented the code below to redirect to a specific page when the w, s, a, d keys are pressed. <script> document.addEventListener('keydown', function(e){ e = e || window.event; key = e.keyCode || e.charCode; var keys = { 87: &ap ...

In my React application, I have integrated p5 sketches that constantly loop and repeat

Currently facing a challenge integrating p5 sketches into my React App. I've tried adjusting the z Index of the toolbar to place the p5 elements underneath, but they end up repeating instead. Check out the repository here (sketches can be found in the ...

Utilizing Angular.js to retrieve data from the server and automatically update at specified intervals

I attempted to create a basic app that displays the newest message from each member. Initially, it loads an array of members. Then I invoke a function called refreshMsg to iterate through the array. Within the iteration, I set a timer on it. Unfortunate ...