pmnazar pmnazar - 1 month ago 11
AngularJS Question

Angular ui-router nested view routers not work

Why this routes not working? How to force this code work? How to implement layouts work in angular-ui-router? Please help resolve this problem.

$stateProvider
.state( 'layout', {
abstract: true,
url: '',
views: {
'layout': { templateUrl: 'template/layout.html' },
'header': {
templateUrl: 'template/header.html',
controller: 'HeaderController'
},
'sidebar': { templateUrl: 'template/sidebar.template.html' }
}
} )
.state( 'layout.home', {
url: '/',
views: {
'main@layout.home': { templateUrl: 'template/main.html' }
}
}
);


layout.html

<main class="layout">
<div ui-view="header"></div>
<div class="main">
<div class="container">
<div class="row">
<div class="col-md-9">
<div class="content">
<div ui-view="main"></div>
</div>
</div>
<div class="col-md-3">
<div ui-view="sidebar"></div>
</div>
</div>
</div>
</div>
</main>


index.html

<div ui-view="layout"></div>

Answer

This should work

.state( 'layout', {
    abstract: true,
    url: '',
    views: {
        'layout': { templateUrl: 'template/layout.html' },
        'header': {
            templateUrl: 'template/header.html',
            controller: 'HeaderController'
        },
        //'sidebar': { templateUrl: 'template/sidebar.template.html' }
        'sidebar@layout': { templateUrl: 'template/sidebar.template.html' }
    }
} )
.state( 'layout.home', {
    url: '/',
    views: {
        //'main@layout.home': { templateUrl: 'template/main.html' }
        'main': { templateUrl: 'template/main.html' }
    }
}

The parent state 'layout' - is now targeting 'sidebar@layout' - using absolute naming, to find a template inside of the 'template/layout.html'

The child view is simply using parents target 'main' so we do not need absolute naming. And if we want, it would be just

'main@layout': { templateUrl: 'template/main.html' }

because we target parent's 'layout' target ui-view="main"

Working example could be found here (with some more details)

Comments