【问题标题】:How to nest ng-view inside ng-include?如何在 ng-include 中嵌套 ng-view?
【发布时间】:2013-05-16 11:20:31
【问题描述】:

尝试在ng-include 中添加ng-view 时,没有任何反应。例如在以下代码中,当 themes/midnight/index.html 持有 ng-view 时,不会呈现视图:

<ng-include src="'themes/midnight/index.html'"></ng-include>

但是,如果我使用下面的代码,视图会显示两次:

<ng-include src="'themes/midnight/index.html'"></ng-include>
<div ng-view></div>

问题是什么,我该如何解决?

【问题讨论】:

  • 你是什么意思“这没有显示任何与视图相关的东西:”?
  • 我的意思是 ng-view 没有出现。
  • 您在路由中使用template-src 吗?更多的代码将是可观的:-)。 ng-view 供使用视图$routeProvider.when(, {template-url: '...'});
  • 当然,ng-include 之外的 ng-view 可以工作。只有 ng-include 内的 ng-view 不会出现。当我在 ng-include 内部和外部声明 ng-view 两次时,它会出现两次。对我来说很奇怪。
  • 我实际上遇到了同样的问题。你解决了吗?

标签: angularjs angularjs-ng-include ng-view


【解决方案1】:

由于ng-view 的延迟实例化(通过ng-include)而发生此问题。在这种情况下,$route 实例化也会延迟,$route 将错过位置更改事件(并且根本不会执行路由)。

要绕过这一点,请在应用程序初始化时调用 $route 更新函数:

yourApp.run(['$route', function($route)  {
  $route.reload();
}]);

此外,仅包含 $route 作为依赖项就足够了。这也可以:

yourApp.run(['$route', angular.noop]);

来源:相关issue on github


还可以查看 ui-router,它旨在专门处理嵌套视图的问题。

【讨论】:

  • 有趣,但实际上在主控制器中注入 $route 就足够了——这解决了我的问题))
  • @KOHb - 这相当于将其声明为应用程序的依赖项。
  • 如何声明应用程序的依赖关系?这就是你的意思:angular.module('Main', [dependencies here])
  • @KOHb - 我的意思不是应用程序级别的依赖 - 只是使用 DI 请求服务(如答案所示)。
  • 这也是我的意思 - 只需注入 $route 即可为我修复它,我什至不必调用 $route.reload()。因此,通过添加 $route 参数 DI 开始并创建 $route 对象 - 我的猜测是在构造函数中发生了一些事情,因为这对我来说已经足够了。谢谢!
猜你喜欢
  • 1970-01-01
  • 2014-09-29
  • 2017-02-07
  • 2014-06-25
  • 2016-03-26
  • 2016-07-25
  • 2014-01-24
  • 2016-01-04
  • 1970-01-01
相关资源
最近更新 更多