使用ui-router在父视图中注入模板

时间:2015-06-15 17:27:01

标签: angularjs nested angular-ui-router state

我有一个声明为

的抽象状态
$stateProvider.state('myapp', {
    abstract: true,
    templateUrl : 'index.html'
});

&#39; index.html&#39;中的所有<ui-view>模板将由子状态填充:

$stateProvider.state('myapp.home', {
    url : "/",
    views : {
        "main" : {
            controller : 'HomeCtrl',
            templateUrl : 'includes/home.html'
        }
    }
});

我不明白为什么来自本地状态的模板不会在父命名视图中注入,但在使用"main@"作为视图名称时它可以正常工作。

如果我理解正确,"@"会定位绝对根状态,只使用"main"定位父状态。

但是,抽象状态不是myapp.home的父级吗?

由于

2 个答案:

答案 0 :(得分:2)

您正在使用命名视图。使用main @指定子视图将添加到名为“main”的ui-view中。如果您的父级没有任何名为main的ui-view,则不会在html中插入视图。

对于父子关系,您无需需要命名视图。只需将您的状态更新为以下状态即可。此外,您还必须从html中的ui-view中删除该名称。

$stateProvider.state('myapp.home', {
    url : "/",
   controller : 'HomeCtrl',
   templateUrl : 'includes/home.html'

});

答案 1 :(得分:2)

我想说,我们的超级根状态'myapp'使用名为 index.html 的模板这一事实可能会产生很大的混淆。

我建议更改该命名,然后this adjusted example应该有效。 index.html将仅用作起始页面(引用angular,UI-Router ...)

<!DOCTYPE html>
<html ng-app="MyApp" ng-strict-di>

  <head>
    <title>my app</title>
    <script src="angular.js"></script>
    <script src="angular-ui-router.js"></script>
    <script ...
  </head> 

  <body>
    // place for our root state        
    <div ui-view=""></div>

  </body> 

</html>

现在,我们可以针对这种ui-view 3方式。我们可以将隐式或显式相对或显式的aboslute命名构建用作 viewName@stateName 。这三个定义是相同的:

// I. no views : {} needed, we target parent unnamed
.state('myapp', {
    abstract: true,
    templateUrl: 'tpl.myapp.html'
})
// II. we target explicit parent unnamed view - relative notation
.state('myapp', {
    abstract: true,
    views : {
        '': {
            templateUrl: 'tpl.myapp.html'
        }
    }
})
// III. we target explicit parent unnamed view - absolute notation
.state('myapp', {
    abstract: true,
    views : {
        '@': { // before @ is view name, after @ is state name, empty for root
            templateUrl: 'tpl.myapp.html'
        }
    }
})

正如我们所能说的那样,对于&#39; myapp&#39;我们使用了不同的 templateUrl: 'tpl.myapp.html' 。它的内容与index.html不同,可能是:

<div>
  <h2>the root myapp template</h2>

  place for child states:
  <div ui-view="main"></div>

</div>

现在我们必须以明确的方式定位此视图(但可以是相对的或绝对的:

  .state('myapp.home', {
      url: "/",
      views: {
        // could be "main@myapp" as well
        "main": {
          controller: 'HomeCtrl',
          templateUrl: 'includes/home.html'
        }
      }
  })

检查示例here

在这里阅读更多相关信息: