【问题标题】:Utilize ng-include with raw (or compiled) HTML versus a template URL?将 ng-include 与原始(或编译的)HTML 与模板 URL 结合使用?
【发布时间】:2014-06-15 22:53:33
【问题描述】:

假设我有一个模板,其中包含一个带有 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 中使用模板URL,而是使用原始或编译的HTML?如果没有,是否有另一种 Angular 替代方案可以让我完成此任务,无论是作为某种包含还是部分,但能够包含原始/编译的 HTML?

【问题讨论】:

    标签: javascript angularjs templates angularjs-directive browserify


    【解决方案1】:

    我自己为此花了几天时间,并使用 $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 代码如“
      ”,Browserify 失败并出现以下错误:“>> Error: Line 1: Unexpected token
    • 没关系,我找到了解决方案并将其添加为可能的答案。不过感谢您的指点!
    • @neric foo.html 是直接的 html。你不使用 module.export
    【解决方案2】:

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

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

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

    【讨论】:

    • 我不知道这解决了我的问题;我正在尝试通过 browserify 使用 require 语句将模板简化到构建中。将模板直接放在父模板中作为由脚本标签包围的 HTML 不允许我这样做。我希望将 HTML 直接简化为模板包含/占位符,而不是使用包含或继续将模板添加到 Angular 的模板缓存中。我将在问题中添加另一个示例。
    【解决方案3】:

    我已经修改了 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>
    

    效果很好!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-12
      • 1970-01-01
      • 2018-11-14
      • 2018-07-18
      • 2018-02-19
      • 1970-01-01
      相关资源
      最近更新 更多