Angular ui-router : Parent & Child Views

2019-02-10 02:15发布

I want to build a site with the following structure header-view, main-view, footer-view . So I defined a root route which contains the header & footer. Children of root will be all my sites.Within these sites I will have more nested views.

In the code below it does show the header, but not the footer & the main view. As soon as I remove the parent inheritance, it shows the main view but not the header & the footer.

HTML

<body ng-app="App">
    <header ui-view="header"></header>
    <main ui-view></ui-view>
    <footer ui-view="footer"></footer>
</body>

JS

   module.config(function($urlRouterProvider, $stateProvider) {
      $urlRouterProvider.otherwise('/home');
      $stateProvider
        .state('root', {
          abstract: true,
          views: {
            '@': {
                controller: 'RootCtrl',
                controllerAs: 'rootCtrl'
            },
            'header@': {
                templateUrl: 'modules/header/header.html',
                controller: 'HeaderCtrl',
                controllerAs: 'headerCtrl'
            },
            'footer@': {
                templateUrl: 'modules/footer/footer.html',
                controller: 'FooterCtrl',
                controllerAs: 'footerCtrl'
                }
           }
        })
        .state('root.home',{
            parent:'root',
            url:'',
            templateUrl:'modules/home/home.html',
            controller: 'HomeController',
            controllerAs:'homeCtrl'
        });
    });

1条回答
戒情不戒烟
2楼-- · 2019-02-10 03:09

There is a link to working plunker.

The UI-Router logic how to find a target/anchor for a view is: always try insert child into parent. If not possible, then use absolute naming. see:

View Names - Relative vs. Absolute Names

So what I changed, is, that the parent unnamed view is now containing a target/anchor for a child - unnamed view <ui-view />:

.state('root', {
  abstract: true,
  views: {
    '@': {
        template: '<ui-view />', // NEW line, with a target for a child
        controller: 'RootCtrl',
        controllerAs: 'rootCtrl'
    },
    ....

Also, because we say, that the default url is

  $urlRouterProvider.otherwise('/home');

we have to have such state:

.state('root.home',{
    parent:'root',
    url:'/home', // this is the otherwise, to have something on a start up

Check it here

Another approach with a plunker here, could be to target the root view in the child:

.state('root.home',{
    parent:'root',
    url:'/home',
    views: {
      '@': {
      templateUrl:'home.html',
      controller: 'HomeController',
      controllerAs:'homeCtrl'
      }
    },

In this case, the parent state does not have to have <ui-view /> - we target root, but we won't be inheriting anything... Why is that? See this link:

Scope Inheritance by View Hierarchy Only

查看更多
登录 后发表回答