Angular UI路由器嵌套视图

时间:2014-08-30 22:29:27

标签: javascript angularjs angular-ui angular-ui-router

我有这样的结构:

<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字段。我怎么能这样做?

1 个答案:

答案 0 :(得分:10)

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

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

.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是视图指令中使用的名称,州名是州的绝对名称,例如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

example有类似想法,后面有一些layout.html ......

相关问题