ua_boaz ua_boaz - 4 months ago 58
AngularJS Question

angular ui-router - nested controller - parent controller is initiated twice if child controller is in the same state

.state('home', {
url: '/home',
views: {
'main': {
templateUrl: './main.html',
controller: 'mainController'
},
'parent@home': {
templateUrl: './parent.html',
controller: 'parentController'
},
'child@home':{
templateUrl: './child.html',
controller: 'childController'
},
'otherPage@home': {
templateUrl: './other-page.html',
controller: 'otherController'
}
}
})


In parent.html i have the child view . Basically the parent controller (parentController) is initiated twice in this setup. If i remove the child@home state, the parentController is initiated only once. What am i doing wrong, is there a better way to define these states?

index.html



<div class="maincontent" ui-view="main"></div>


main.html



<div class="maincontent container-fluid" ui-view="parent"></div>
<div class="maincontent container-fluid" ui-view="otherPage"></div>


parent.html



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

Answer

Redefine the state like this:

.state('home', {
    url: '/home',
    views: {
        '': {
            templateUrl: './main.html',
            controller: 'mainController'
        },
        'parent@home': {
            templateUrl: './parent.html',
            controller: 'parentController'
        },
        'child@home':{
            templateUrl: './child.html',
            controller: 'childController'
        },
        'otherPage@home': {
            templateUrl: './other-page.html',
            controller: 'otherController'
        }
    }
})

Form my understanding, the view with the empty key would be loaded as the default for the home state.

Done this way, your main.html template would then contain pointers to other ui-views as you've done with parent and otherPage.

I've not been able to test this because I'm not on my dev PC but I think it should work because it's the format followed in a couple of my AngularJS projects.