【问题标题】:ng-include doesn't do anythingng-include 不做任何事情
【发布时间】:2019-05-06 07:38:15
【问题描述】:

我正在尝试使用 ng-include 在我的软件网页上包含一些 HTML,但我似乎无法让它工作。目前,我将最终目标的简化版本用于测试目的。

我的项目树的相关sn-p:

-web
--dragonweb
---src
----app
-----dragon
-------dragon.css
-------dragon.html
-------dragon.spec.ts
-------dragon.ts
-------test.html

dragon.html

<div ng-app = "" ng-controller="test">
    testing
    <div ng-include="" src="'app/src/dragon/test.html'"></div>
</div>

test.html

<div>
    This is an included file
</div>

网页上的预期输出:

测试

这是一个包含的文件。

网页上的实际输出:

测试

我尝试过使用不同长度的 test.html 路径,但没有成功。我也一直在使用 ng-controller 标签和 ng-include 标签的语法,但没有运气。网页中没有控制台错误。知道为什么它似乎不起作用吗?

背景故事/免责声明:我是这个项目的实习生,在首席开发人员突然离开后继承它之前,这是我第一次做任何类型的 Web 开发,我只是在反复试验中学习工作。因此,如果我做的事情非常不正确,我绝对会全力以赴地改进这个过程!我选择尝试使用 ng-include 是因为我们已经实现了 Angular,并且根据我的研究,这在理论上似乎是实现我想要的最简单的方法。

【问题讨论】:

  • Chekc this out:: docs.angularjs.org/api/ng/directive/ngInclude 你可以尝试做一个相对 url 看看它是否 lodas: EX: src="'./test.html'"&gt;&lt;/div&gt;
  • 检查开发者控制台是否有错误。由于代码使用ng-app=""ng-controller="test" 指令将产生运行时错误。 Error: [$controller:ctrlreg] The controller with the name 'test' is not registered.errors.angularjs.org/1.7.5/$controller/ctrlreg?p0=test
  • 感谢您的意见!不幸的是,无论我进行什么更改,都不会为此创建控制台错误。在我继承该项目的控制权之前,有几个控制台错误,所以我假设(希望?)它们不相关。

标签: angularjs angularjs-ng-include


【解决方案1】:

您需要将 src 传递给 ng-include 指令而不是 src 属性: 例如:

<div ng-include="'app/src/dragon/test.html'"></div>

或使用相对路径:

<div ng-include="'./test.html'"></div>

详情请查看official documentation

用法: 作为元素

<ng-include
  src="'string_url'">
...
</ng-include>

作为属性

<ANY_ELEMENT_TAG
  ng-include="'string_url'">
...
</ANY_ELEMENT_TAG>

作为 CSS 类:

<ANY class="ng-include: string; [onload: string;] [autoscroll: string;]"> ... </ANY>

【讨论】:

  • 谢谢!我将 dragon.html 编辑为:&lt;div ng-app = "" ng-controller="test"&gt; testing &lt;div ng-include="'./test.html'"&gt;&lt;/div&gt; &lt;/div&gt; ,但它仍然无法正常工作。是否有可能项目的另一部分不允许这样的事情起作用?我对使用 Angular 和 Web 开发非常陌生,所以我不完全确定哪些潜在问题可能会影响到这一点。
  • 我尝试将它用作元素&lt;ng-include src="'./test.html'"&gt;&lt;/ng-include&gt;,它告诉我“ng: 'ng-include' 不是已知元素...”。这可能是我的问题吗?如果是这样,我如何让它成为模块的一部分?
  • 为什么你有ng-app 作为“”。 ng-app 应该有一些价值,这会将角度附加到 DOM
  • 如果这不起作用,请检查浏览器控制台是否有任何 404。确保你在 ng-include 之外有 ng-app!
  • 在尝试对 ng-include 进行故障排除时,老实说只是遵循人们的示例。如果我在 ng-app 中输入一个值,它是否需要对应于其他任何内容?就像我说的那样,我尝试过的任何东西都没有产生任何控制台错误。
猜你喜欢
  • 2020-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
相关资源
最近更新 更多