Angularjs ui-router :条件嵌套名称视图

Angularjs ui-router : conditional nested name views

本文关键字:视图 嵌套 条件 ui-router Angularjs      更新时间:2023-09-26

按照教程:

http://scotch.io/tutorials/javascript/angular-routing-using-ui-router

和演示:

http://scotch.io/demos/angular-ui-router#/about

在 关于 页面上,有两个命名视图,"列一"和"列二"。

是否可以有条件地实例化命名视图,如果某些条件失败,命名视图"columnOne"并且其控制器不应实例化,并且其在页面上的位置留空。

我想避免在不希望控制器加载时使用 ng-if,从而节省控制器可能具有的 API 调用。

类似于在解析块中拒绝,但对于同级命名视图。

UI Router 为我们提供了两个"秘密调味料",templateProvider 函数和 $templateFactory 服务。

可以注入的模板提供程序函数可以访问 本地,并且必须返回模板 HTML。

因此,在此函数中,您可以设置条件以呈现命名视图的模板。 templateProvider()只允许我们返回 HTML,但假设我们想返回一个模板,为了可读性或您可能有的任何原因。这就是我们使用$templateFactory并调用.fromUrl()的地方:

$templateFactory.fromUrl(( 通过 $http 从 URL 加载模板,并且 $templateCache。

views: {
  'columnOne': {
    controller: 'SomeCtrl',
    templateProvider: function($templateFactory) {
      // if condition is true, return the template for column one
      return $templateFactory.fromUrl('path/to/template.html');
    }
  },
  'columnTwo': {
    controller: 'MaybeSomeOtherCtrl',
    templateProvider: function($templateFactory) {
      // if condition is true, return the template for column two
      return $templateFactory.fromUrl('path/to/template.html');
    }
  }
}