ng-include 的正确语法是什么?

2022-08-29 23:27:25

我正在尝试在 中包含 HTML 代码段,但我无法使包含起作用。似乎当前的语法与以前不同:我看到许多示例使用ng-repeatng-include

<div ng-include src="path/file.html"></div>

但是在官方文档中,它说要使用

<div ng-include="path/file.html"></div>

但是,在页面下方,它显示为

<div ng-include src="path/file.html"></div>

无论如何,我试过了

<div ng-include="views/sidepanel.html"></div>
<div ng-include src="views/sidepanel.html"></div>
<ng-include src="views/sidepanel.html"></ng-include>
<ng-include="views/sidepanel.html"></ng-include>
<ng:include src="views/sidepanel.html"></ng:include>

我的片段不是很多代码,但它有很多事情要做;我在ng-repeat内部动态加载模板中读到这可能会导致问题,所以我只用单词替换了的内容,但仍然没有。sidepanel.htmlfoo

我还尝试直接在页面中声明模板,如下所示:

<script type="text/ng-template" id="tmpl">
    foo
</script>

并运行引用脚本的所有变体,但仍然一无所获。ng-includeid

我的页面里面有很多,但现在我已经把它剥离成这样:

<!-- index.html -->
<html>
<head>
<!-- angular includes -->
</head>
<body ng-view="views/main.html"> <!-- view is actually set in the router -->
    <!-- views/main.html -->
    <header>
        <h2>Blah</h2>
    </header>
    <article id="sidepanel">
        <section class="panel"> <!-- will have ng-repeat="panel in panels" -->
            <div ng-include src="views/sidepanel.html"></div>
        </section>
    </article>
<!-- index.html -->
</body>
</html>

标头会呈现,但我的模板不会呈现。我在控制台或 Node 中没有收到任何错误,如果我在开发工具中单击链接,它会将我带到我的模板(并显示)。src="views/sidepanel.html"foo


答案 1

您必须在双引号内对字符串进行单引号引用:src

<div ng-include src="'views/sidepanel.html'"></div>


答案 2
    <ng-include src="'views/sidepanel.html'"></ng-include>

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

    <div ng-include src="'views/sidepanel.html'"></div>

要记住的要点:

--> src 中没有空格

--> 记得在双引号中使用单引号作为src