Angular UI路由器嵌套视图

Angular UI router nested views

本文关键字:视图 嵌套 路由器 UI Angular      更新时间:2023-09-26

我有一个这样的结构:

<div ui-view="main">
  <!-- content populated here by AngularJS ui-router -->
  <aside ui-view="sidebar">
    <!-- content populated here by AngularJS ui-router -->
  </aside>
</div>

我希望能够像下面这样在主状态下定义模板,而不必在子状态下管理它。

.state('state1', {
  url: '/',
  views: {
    'main': {
      templateUrl: '/modules/blog/partials/index.html',
      controller: 'BlogController'
    },
    'sidebar': {
      templateUrl: '/modules/core/partials/sidebar.html'
    }
  }
});

我希望名为sidebar的ui视图不是main的子状态,而是由main状态的视图对象填充,而不是由子状态的templateUrl字段填充。我该怎么做?

我们可以在一个状态中使用更多视图,请参阅:

  • 多个命名视图

定义只需要使用绝对命名:

.state('state1', {
  url: '/',
  views: {
    'main': {
      templateUrl: '/modules/blog/partials/index.html',
      controller: 'BlogController'
    },
    // instead of
    // 'sidebar': {
    // we need
    'sidebar@state1': {
      templateUrl: '/modules/core/partials/sidebar.html'
    }
  }
});

如这里详细解释的:

  • 视图名称-相对名称与绝对名称

在幕后,每个视图都会被分配一个绝对名称,该名称遵循viewname@statename的方案,其中viewname是视图指令中使用的名称,state name是状态的绝对名称,例如contact.item。您还可以选择用绝对语法编写视图名称。

因此,正如上面的片段所示,如果的内容

 /modules/blog/partials/index.html

将是:

<div>
  <!-- content populated here by AngularJS ui-router -->
  <aside ui-view="sidebar">
    <!-- content populated here by AngularJS ui-router -->
  </aside>
</div>

index.html将包含占位符:

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

然后

  • 'main'-将在父根目录(index.html)中搜索
  • 'sidebar@state1'将在"state1"(本身)中评估为viewName/target

一个有类似想法的例子,后面有一些layout.html