如何使用ng-include与原始(或已编译)HTML相比使用模板URL?

6

假设我有一个包含 ng-include 指令的元素的模板:

<div ng-include src="'templates/top-promo-content.html'"></div>

我试图将所有模板整合到我们的构建应用JS中(使用browserifybrfs转换),概念上来说,这将会是这样的:

<div ng-include src="fs.readFileSync('./templates/top-promo-content.html', 'utf8')"></div>

最终导致的结果是:
<div ng-include src="<ul><li>list item</li></ul>"></div>

有没有办法在ng-include中使用原始或编译后的HTML,而不是使用模板URL?如果没有,是否有其他替代方案可以在Angular中实现这一点,例如某种包含或部分,但具有包括原始/编译后的HTML的能力?
3个回答

6

我自己花了几天时间,并使用了 $templateCache 找到了一个很好的解决方案。

Javascript

app.run(['$templateCache', function($templateCache) {
    //Add ng-include templates to template cache
    $templateCache.put('foo.html', require('./templates/foo.html'));
    $templateCache.put('bar.html', require('./templates/bar.html'));
}]);

html

<ng-include="'foo.html'"></ng-include>

这将包括在您的 bundle.js 中的模板。
此外,如果您正在运行 watchify 进行重新捆绑,则对模板进行的任何更改都将导致 watchify 触发重新捆绑并使用新模板进行实时刷新。

“foo.html”文件中确切包含了什么内容?如果我在HTML代码中加入类似于“<div></div>”的标签,Browserify会报错:“>> Error: Line 1: Unexpected token <”。看起来它真正期望的是JavaScript代码。 - neric
没关系,我找到了解决方案,并将其作为可能的答案添加了进去。不过还是谢谢你的指针! - neric
@neric foo.html 是纯 HTML。你不需要使用 module.export。 - Malkus

2
我已经根据Malkus的答案对其进行了修改以使其在我的情况下工作: Javascript:
app.run(['$templateCache', function($templateCache) {
    //Add ng-include templates to template cache
    $templateCache.put('foo.html', fs.readFileSync('/templates/foot.html').toString());
}]);

HTML

<ng-include="'foo.html'"></ng-include>

工作得很好!


2

使用script标签可以在页面上包含模板。

<script type="text/ng-template" id="templates/top-promo-content.html">
  <ul><li>list item</li></ul>
</script>

这将模板放入模板缓存中,ng-include指令从那里获取它。对于每个通过URL获取模板的指令都是如此。


1
我不确定这是否解决了我的问题;我正试图通过使用browserify的require语句将模板整合到构建中。将模板直接作为HTML放在父模板中,并用script标签包围起来,无法实现此目的。我希望能将HTML直接整合到模板的include/placeholder中,而不是使用include或继续添加模板到Angular的模板缓存中。我会在问题中添加另一个示例。 - J. Ky Marsh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接