如果子控制器处于相同状态,则angular ui路由器-嵌套控制器-父控制器将启动两次

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

本文关键字:控制器 启动 嵌套 两次 路由器 于相同 状态 ui angular 如果      更新时间:2023-09-26
.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'
        }
    }
})

在parent.html中,我有子视图。基本上,父控制器(parentController(在此设置中启动两次。如果我删除child@home状态下,parentController只启动一次。我做错了什么,有更好的方法来定义这些状态吗?

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>

像这样重新定义状态:

.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'
        }
    }
})

根据我的理解,带有空键的视图将作为主状态的默认视图加载。

通过这种方式,您的main.html模板将包含指向其他ui-views的指针,就像您对parentotherPage所做的那样。

我没能测试这个,因为我不在我的开发PC上,但我认为它应该能工作,因为它是我的几个AngularJS项目中遵循的格式。