利用原始(或编译)HTML与模板URL的ng-include?

J. *_*rsh 6 javascript templates angularjs browserify angularjs-directive

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

<div ng-include src="'templates/top-promo-content.html'"></div>
Run Code Online (Sandbox Code Playgroud)

我正在尝试将所有模板简化为我们构建的应用程序JS(使用browserifybrfs转换),从概念上讲,它看起来像:

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

哪个最终会导致:

<div ng-include src="<ul><li>list item</li></ul>"></div>
Run Code Online (Sandbox Code Playgroud)

有没有办法,而不是使用模板URL,而不是使用ng-include原始或编译的HTML?如果没有,是否有另一种角度的替代方案可以让我实现这一点,或者作为某种包含或部分,但是能够包含原始/编译的HTML?

Mal*_*kus 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'));
}]);
Run Code Online (Sandbox Code Playgroud)

HTML

<ng-include="'foo.html'"></ng-include>
Run Code Online (Sandbox Code Playgroud)

这将包括bundle.js中的模板.

另外如果你watchify想要重组; 对模板的任何更改都会导致watchify触发重新绑定并使用新模板进行实时刷新.


a b*_*ver 2

模板可以包含在带有script标签的页面上。

<script type="text/ng-template" id="templates/top-promo-content.html">
  <ul><li>list item</li></ul>
</script>
Run Code Online (Sandbox Code Playgroud)

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