AngularJS - navigating between sibling states using ui-router

I am currently incorporating bootstrap along with angularjs (and utilizing ui-router for routing).
Within my navbar, each tab click should display a nested navbar within it. The nested navbar acts as a ui-view (is there a better way to approach this?).
The issue I am encountering is that when I click on one li in the main navbar, all four nested navbar views are displayed.

div(ng-controller='MyCtrl')
h1 Header
ul.nav.nav-tabs(role="tablist")
    li.active(role="presentation")
        a(ui-sref='first_nested_state') General
        div(ui-view)
    li.active.navbar-padding-left(role="presentation")
        a(ui-sref='second_nested_state') User
        div(ui-view)
    li.active.navbar-padding-left(role="presentation")
        a(ui-sref='third_nested_state') User
        div(ui-view)
    li.active.navbar-padding-left(role="presentation")
        a(ui-sref='fourth_nested_state') User
        div(ui-view)

Here is an example of one nested navbar (all follow the same structure, but differ in names):

div(ui-view)
ul.nav.nav-tabs(role="tablist", color="red")
  li.active(role="presentation")
     a(ng-href='#') A
  li.active(role="presentation")
     a(ng-href='#') B
  li.active(role="presentation")
     a(ng-href='#') C

Below is my state configuration:

 $stateProvider
    .state('main_nav_bar', {
          url: '/main_nav_bar',
          templateUrl: 'main_nav_bar.html'
      })
    .state('first_nested_navbar', {
        parent: 'main_nav_bar',
        url: '/first_nested_navbar',
        templateUrl: 'first_nested_navbar.html'
      })
    .state('second_nested_navbar', {
        parent: 'mainNavBar',
        url: '/second_nested_navbar',
        templateUrl: 'second_nested_navbar.html'
      })

In addition to coffeescript and jade, I am using these technologies as well.

Answer №1

The problem at hand ("...when I click one <li>...all of the four nested navbar views are shown...") stems from the repetitive declaration of div(ui-view)

This indicates that there are 4 instances of <div ui-view></div> in the page's DOM. Each of these is being utilized as a destination for specific content, resulting in it being rendered multiple times.

To rectify this issue, utilizing named views is the solution:

Refer to: Multiple Named Views

In our scenario, the HTML structure should be defined as follows:

li.active(role="presentation")
    a(ui-sref='first_nested_state') General
    div(ui-view="first") // assign it the name "first"
li.active.navbar-padding-left(role="presentation")
    a(ui-sref='second_nested_state') User
    div(ui-view="second") // assign it the name "second"
...

Furthermore, explicit view definitions for our states should be implemented:

...
.state('first_nested_navbar', {
    parent: 'main_nav_bar',
    url: '/first_nested_navbar',
    views : {
      'first' : {   // explicitly injected into the anchor/target "first"
        templateUrl: 'first_nested_navbar.html'
      },
    }
  })
.state('second_nested_navbar', {
    parent: 'mainNavBar',
    url: '/second_nested_navbar',
    views : {
      'second' : { // targeting the ui-view="second"
        templateUrl: 'second_nested_navbar.html'
      },
    }
  })

For a detailed example and explanation, refer to the extensively documented illustration here, extracted from the given source:

$stateProvider
  .state('contacts', {
    // Automatically inserted into the unnamed ui-view 
    // within the parent state template. Since this is a main level state, 
    // its parent state template is index.html.
    templateUrl: 'contacts.html'   
  })
  .state('contacts.detail', {
    views: {
        ////////////////////////////////////
        // Relative Targeting             //
        // Targets parent state ui-view's //
        ////////////////////////////////////

        // Relatively targets the 'detail' view in the parent state, 'contacts'.
        // <div ui-view='detail'/> inside contacts.html
        "detail" : { },            

        // Relatively targets the unnamed view in this state's parent state, 'contacts'.
        // <div ui-view/> inside contacts.html
        "" : { }, 

        ///////////////////////////////////////////////////////
        // Absolute Targeting using '@'                      //
        // Targets any view within this state or an ancestor //
        ///////////////////////////////////////////////////////

        // Absolutely targets the 'info' view in this state, 'contacts.detail'.
        // <div ui-view='info'/> inside contacts.detail.html
        "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e28b8c848da2818d8c9683819691cc868796838b8e">[email protected]</a>" : { }

        // Absolutely targets the 'detail' view in the 'contacts' state.
        // <div ui-view='detail'/> inside contacts.html
        "detail@contacts" : { }

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 is the proper method to call an async function as the main function?

I have a series of nodejs scripts that are designed to complete a task and terminate, rather than run continuously. These scripts utilize async functions, like the example below: const mysql = require('mysql2/promise'); ... async function main ...

Vue3 CheckBox Component: A versatile option for interactive user interfaces

Struggling with incorporating checkboxes into a separate component. I have a child component with a basic card template and checkbox - essentially, a product list where each card should have a checkbox for deletion. Currently, as I loop through an array to ...

Tips for incorporating HTML from a Controller into an AngularJS directive template - encountering interpolation issue "Can't interpolate"

Within my AngularJS controller, there is a function: //some stuff from controller var variable1; var variable2; $scope.setTitle = function () { if ( //sth) { variable1 = "string" return variable1; ...

Tips for avoiding the push method from replacing my items within an array?

Currently, I am diving into Typescript and VueJS, where I encountered an issue with pushing elements to my array. It seems to constantly override the 'name' property. Let me share the code snippet causing this problem: const itemsSelectedOptions ...

When selecting an old list, only the most recently created ID is displayed, rather than the ID of the specific list being

I've set up a dashboard where I can create lists and have them displayed on the screen, but there seems to be an issue when trying to open any list as only the last created one opens. Can anyone point out what mistake I might be making? The technologi ...

Adding 2-dimensional text to a specified location with the help of three.js

let startPosition = new THREE.Vector3(-5,0,0); let targetPosition = new THREE.Vector3(-5,2,0); let directionVector = new THREE.Vector3().sub(targetPos,startPosition); let arrowHelper = newTHREE.ArrowHelper(directionVector.clone().normalize(),startPosition, ...

Are you familiar with the Pagination and Card Components offered by Ant Design (antd)?

Can you merge the Pagination feature from antd with Card components to create a layout resembling Pinterest, complete with pagination? The standard Pagination code from https://ant.design/components/pagination/: import { Pagination } from 'antd&apo ...

Customizing Bootstrap styles when toggling

I have been working on incorporating a dark/light theme into my project. By creating a separate SCSS file that is imported after the main Bootstrap file, I was able to override certain core Bootstrap styles to achieve a dark/light mode. Now, I am facing th ...

What is the best way to transfer an integer from my main application to a separate JavaScript file?

Currently, I am developing a complex code using React Bootstrap and focusing on creating a Dropdown list that fetches data from the backend database. <Dropdown> <Dropdown.Toggle variant="success" id="dropdown-basic"></D ...

invoking both componentDidMount and componentDidUpdate within the identical code block

componentLifeCycleMethod() { let data ; axios.get('http://localhost:8000/wel/') .then(res => { data = res.data; this.setState( { details: data }); }) .catch(err => {}) } I am looking to opt ...

Accessing a variable from an external JavaScript file using jQuery

Can someone help me out with this issue I'm facing? I am having trouble getting a string returned to a variable in my embedded Javascript code. token.js: function token () { return "mysecretstring"; } HTML Code: <!DOCTYPE html> <h ...

Add elements continuously without the need to refresh the page

How can I dynamically create a variable value by combining two different inputs without having to reload the page Here is the code snippet: {exp:safecracker channel="blending_log" return="sthome/blending/ENTRY_ID"} <h3>Select and enter data</h3 ...

Is it possible to configure Nginx mime types within a Docker container?

My docker-compose.yml file looks like this: version: "1.0" services: web: container_name: webserver image: nginx volumes: - ./nginx.conf:/etc/nginx/nginx.conf:ro - ./frontend:/frontend ports: - "8001:80&qu ...

Creating webpages dynamically by utilizing Javascript

I need assistance with a task involving a list of elements that allows users to print only the clicked element, rather than the entire page. The elements are structured as follows: <div class="element" id="#element1">Element 1</div> <div cl ...

Send a JavaScript variable to Twig

I am trying to pass a JavaScript variable to a twig path but the current method I am using is not working as expected. <p id="result"></p> <script> var text = ""; var i; for (varJS = 0; varJS < 5; varJS++) { text += "<a href= ...

Assigning a value to a hidden field using a Bootstrap radio button

I'm having some difficulty setting the value of a hiddenfield using a Bootstrap radio button. Below is the code for the button group with the radio buttons and the hiddenfield. <div class="myRow"> <div class="smallCol"> ...

Tips for accessing every "results" (parameters) from an API

Here is the response I received after making an API call in my attempt to retrieve each "bloc" result using a .forEach. const app = express(); const axios = require('axios') jobList = []; app.get('/getAPIResponse', function(req, res) ...

The intricacies of how Node.js handles asynchronous execution flow

I wanted to ask about the best approach for displaying data retrieved from MySQL. Do you think this workflow is correct? app.get('/demo/:id', function(req, res) { var query = csql.query('SELECT * FROM table_videos WHERE id=? LIMIT 1' ...

Sending dynamic data through AJAX to a CodeIgniter controller is a common task that allows for seamless

Can anyone help me with retrieving data from a looping form in CodeIgniter? The form works fine, but I'm struggling to fetch the looping data in the controller. Here's my view (form): <form action="#" id="ap_data"> <div class="table-r ...

Differences between Typescript React.ReactElement and JSX.Element

Simple Inquiry: I'm curious about the contrast between React.ReactElement and JSX.Element. Can you clarify if they are interchangeable, and advise on when to opt for one over the other? ...