Angular deep nested router interface

How can I set up nested views in Angular for the following routes?

/#/app/dashboard
/#/app/product/
/#/app/product/new

Here is my current route configuration:

$stateProvider
    .state('app',{
        url: '/app',
        templateUrl: 'views/app.html',
        resolve: loadSequence('modernizr','moment'),
        abstract: true
    })
    .state('app.dashboard', {
        url: '/dashboard',
        templateUrl: 'views/dashboard.html',
        title: 'Dashboard',
        ncyBreadcrumb: {
            label: 'Dashboard'
    }
    }).state('app.product', {
        url: '/product',
        templateUrl: "views/product.html",
        title: 'Buttons',
        resolve: loadSequence('ngTable', 'ngTableCtrl')

    }).state('app.product.new', {
        parent: 'app.product',
        url: '/new',
        templateUrl: "views/add_product.html",
        title: 'Buttons',
        resolve: loadSequence('ngTable', 'ngTableCtrl')
    })

I am facing an issue where navigating to /#/app/product/new redirects me back to /#/app/product. Any idea why this is happening and how nested views work in Angular?

Thank you!

Answer №1

The method you described above is effective. I have created a working plunker to demonstrate the functionality of this state flow:

$stateProvider
    .state('app',{
        url: '/app', 
        templateUrl: 'views/app.html',
        abstract: true
    })
    .state('app.dashboard', {
        url: '/dashboard',
        templateUrl: 'views/dashboard.html'
    }).state('app.product', {
        url: '/product',
        templateUrl: "views/product.html",
    }).state('app.product.new', {
        parent: 'app.product',
        url: '/new',
        templateUrl: "views/add_product.html",
    })

The provided links work correctly and navigate as expected:

<a href="#/app/dashboard">
<a href="#/app/product">
<a href="#/app/product/new">

To ensure that the link

<a href="#/app/product/new/">

navigates to its parent (as specified in the question), you need to set the default redirection like this:

$urlRouterProvider.otherwise('/app/product');

If you use the incorrect link format like

// check the trailing /
<a href="#/app/product/new/">
// this will work
<a href="#/app/product/new">

In conclusion, the concept works well. There is no inherent reason for navigating from #/app/product/new to #/app/product

You can test it here

EXTEND

This is the faulty plunker originally provided. I have fixed it here

The first change was made to index.html - cleaning up unnecessary elements

  1. Deleting incorrect elements
  2. Using the full version of angular to pinpoint the issue

index.html:

<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <link rel="stylesheet" href="style.css" />
    <script data-require="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a2c3ccc5d7cec3d08cc8d1e2938c968c968cda">[email protected]</a>" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.js" data-semver="1.4.6"></script>
    <script data-require="ui-router@*" src="//rawgit.com/angular-ui/ui-router/0.2.15/release/angular-ui-router.js"></script>
    <!--<script>-->
    <script src="app.js"></script> 
  </head> 

The main issue was found in the wrong module reference name 'ui-router' instead of 'ui.router'

app.js

// Incorrect
var app = angular.module('plunker', ['ui-router'])
// Correct
var app = angular.module('plunker', ['ui.router'])

Another crucial point mentioned in comments was to target <div ui-view>. This was added to the parent state 'app.product'.

This ensures that each state (including children) must be injected somewhere, typically its parent. Therefore, the parent state 'app.product' should contain the ui-view target for its child state 'app.product.new'.

For more insights on named views and absolute naming, refer to these discussions:

  • Angular UI Router - Nested States with multiple layouts
  • Angularjs ui-router not reaching child controller
  • Angular ui-router : Container view and Default view

You can find the improved version here

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

Is the availability of XMLHttpRequest constant?

When using XMLHttpRequest to retrieve data from the server with Javascript, is it necessary to include conditional checks for the specific browser being used? Is the code snippet below considered standard practice when working with XMLHttpRequest? if (w ...

Exploring the capabilities of the jQuery `val()` function alongside the dynamic framework

Whenever I have a JavaScript variable that contains HTML printed from a table on my server, I encounter issues when using it in a jQuery function like val(). The problem arises every time someone enters content with special characters like " or '. Thi ...

Disable functionality not functioning properly on button attribute

I've created a demo on JSFiddle here: http://jsfiddle.net/qJdaA/2/. The goal of this code is to disable the button with the ID #monitor if no checkboxes are checked. var checked = $('#status_table tr [id^="monitor_"]:checked'); if (checked. ...

Navigating through an array of functions, some of which may return promises while others do not

Is there a way to efficiently iterate and execute an array of functions where some return promises, requiring the use of await, while most do not return promises, necessitating them to be set as async? for (let i = 0; i < this.steps.length; i++) { ...

Can preloading data from a website impact the accuracy of my google analytics data?

I am interested in creating a simple script that utilizes AJAX to load the content from each page listed in my main navbar into a hidden div on the current page. My goal is to preload important content and cache it on the user's computer to ensure fa ...

Flask Socket-IO - Instant Messaging App with Real-Time Communication, Socket Functionality Not Operating as Expected

I've been dedicating a good amount of time to this flask project, working on incorporating Flask-SocketIO along with JavaScript SocketIO to enable real-time messaging capabilities. Here's the Python section of the code: ## Setting up Socket IO f ...

What is the process of transforming a string into a JSON object?

var str = '""{""as"":""N9K-93180YC-EX""}""'; I attempted to remove the extra quotes using a regular expression: var str1 = str.replace(/\"/g, ""); After removing the extra quotes, the string now looks like "{as:N9K-93180YC-EX}". However, ...

Interplay between Angular controllers and directives

I've been working on a code snippet that allows users to leave comments on a list of items. To achieve this, I created a directive and set it up to listen for keydown events in order to prompt the user to submit a comment by a specific keycode, 13. H ...

Infinite loop readiness with JQuery

My current project involves preloading images and seamlessly fading them in once they are fully loaded using JQuery. To achieve this, I attempted to create an invisible image tag where the images would load before setting the source back to the original im ...

Using regular expressions to extract the value of a specific key from a JavaScript object

After scraping a webpage with BeautifulSoup and requests, I came across this snippet of code within the HTML content: $create(Web.Scheduler, { "model": '{"apt":[0]}', "timeZone": "UTC", "_uniqueI ...

Error message "Undefined error encountered when attempting to display an array of objects using jQuery and PHP through AJAX on the console"

While trying to parse a JSON using jQuery and AJAX, I encountered an issue where some objects in the Array, like the SUM(amountbet) object, are showing up as "undefined" in the console. The image above depicts the SUM(amountbet) object appearing ...

Changing Marker Colors in OpenLayers After Importing GPX Data: A Quick Guide

Check out this link for a code tutorial on importing GPX files and displaying map markers. I successfully implemented this code to show map markers. Is there a way to customize the color of the markers? Edit: var fill = new Fill({ color: 'rgba(2 ...

Implementing clickable table rows in React Router Link for seamless navigation

I'm relatively new to working with React. In my project, there is a Component called Content, which acts as a container for two other components - List and Profile. class Content extends Component{ <HashRouter> <Route exact path="/ ...

The asyncData function in Nuxt is throwing a surprise setTimeout (nuxt/no-timing-in-fetch-data)

Having trouble running a code on my pages/posts/index.vue page where I keep getting an error message 'Unexpected setTimeout in asyncData'. Can anyone provide assistance in understanding this error and suggest if any additional plugins are needed? ...

Adding two input values using jQuery

Here is the function compute() that I am working with: function compute() { if ($('input[name=type]:checked').val() != undefined) { var a = $('input[name=service_price]').val(); var b = $('input[name=modem_pric ...

A "Uncaught TypeError" error occurs when trying to execute a function using the dollar sign

After successfully recognizing the hover function, the console displays an error message: Uncaught TypeError: $ is not a function <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script> $(docume ...

Measuring the height of a div element using Vuejs

Let me explain my current situation: I am trying to determine the height of a DIV component in order to dynamically inform its child component about its size. I have been working on implementing manual loading mode, but I have encountered an issue where t ...

Identify the activation of the "Inspect Element" feature

On Samy Kamkar's personal website at , there is a clever feature that detects when the console is opened and automatically clears the source code/console. It's a fascinating display of coding magic! https://i.stack.imgur.com/kag6U.jpg Curious t ...

What is the most effective method for achieving a desired outcome?

Is it a valid approach to get an action result, and if so, how can this be achieved? For instance, if there is a page with a form for creating entities, after successfully creating an entity, the user should be redirected to the entity's detail view. ...

The tension settings in Chart.JS appear unusual

I recently updated to ChartJS v4.0.1 and noticed a new option called tension for curving the line chart. However, I'm not satisfied with how it looks. The tension option ranges from 0 to 1, and I've experimented with different values to enhance ...