简体   繁体   中英

Angular UI-Router and nested states

I´m trying to get my nested states to work, but I don´t know what I´m doing wrong.

Here is my simple example on plunkr

Body:

<div class="site_container" ui-view></div> 

There I want to show my site-container, which should always been shown:

<header class="main_header">
    <h1>My header</h1>
</header>

<main  ui-view></main>

In the -tag I want to switch between some sub-states, for a simple example I only want to show a :

<h2>My content</h2>

So as result, I want to have:

<div class="site_container" ui-view>
    <header class="main_header">
        <h1>My header</h1>
    </header>

    <main  ui-view>
        <h2>My content</h2>
    </main>
</div> 

Here is my config:

angular.module('myApp').config([
'$stateProvider',
'$urlRouterProvider',
function (
    $stateProvider,
    $urlRouterProvider
    ) {

    $stateProvider

    .state('main', {
        abstract: true,
        url: '/',
        templateUrl: 'app.html'
    })
    .state('main.child', {
        url: '/child',
        templateUrl: 'child.html',
    })

    // if none of the above states are matched, use this as the fallback
    $urlRouterProvider.otherwise('/child');
}]);

Could you tell me, what I´m doing wrong?

As your abstract state has / in the URL that means while you are creating a child state, It can have URL with /child will be considered as //child

Per your current code it should be $urlRouterProvider.otherwise('//child');

Plunkr

But technically for making URL user friendly you should declare abstract state with blank ( '' ) URL

.state('main', {
    abstract: true,
    url: '', //<--changed to blank URL
    templateUrl: 'app.html'
})

Then you could make your code working as you posted in question

Demo Plunkr

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM