在一个外部.html中包含angular模板

Including angular templates on one external .html

本文关键字:html 包含 angular 模板 外部 一个      更新时间:2023-09-26

在angular中,你可以在页面本身创建一个模板,如:

<script type="text/ng-template" id="something.htm">
    <div>This is a template.</div>
</script>

我想知道你是否可以把一堆这样的东西放在一个外部页面,比如"template .htm",然后引用整个页面,基本上是说"在template .htm中查找模板某物。htm"。

如果你不介意性能下降一点,下面是我在评论中所说的一个工作示例。

例子: http://plnkr.co/edit/EcEySnmmm3hsLimDHfYr?p=preview

关键概念是在templates.html加载后删除np-app并手动引导应用程序。

$.get('templates.html').done(function (rawHtml) {
  angular.module('app').run(function ($compile) {
    $compile(rawHtml)({});
  });
  angular.element(document).ready(function () {
    angular.bootstrap(document, ['app']);
  });
});

虽然技术上不能直接回答你的问题,但一个非常干净的解决方案可能是使用html2js。

它将接受你给它的。html模板,并将它们转换成一个或多个.js文件,其中包含填充模板缓存的代码。然后,只需包含生成的.js文件,就完成了。客户端不应该请求。html文件——它会先检查缓存。

它确实需要对构建设置进行一些更改,但可以完全自动化。

这不就像使用ng-include一样简单吗?

      <ng-include  src="'mytemplates.html'"></ng-include>

(注意带有src的单引号)

@Aaron:添加更多关于我所做的信息。这是我的index.html(主页)的正文

      <body ng-app="">
        <ng-include src="'mytemplates.html'"></ng-include>
        <p><a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load external template                    1</a>
        </p>
        <p><a ng-click="currentTpl='/tp2.html'" id="tpl-link">Load external template 2</a>
        </p>
        <p><a ng-click="currentTpl='/tp3.html'" id="tpl-link">Load external template                 3</a>
         </p>
         Content:
        <div id="tpl-content" ng-include src="currentTpl"></div>
        </body>

这里是mytemplate。html

           <script type="text/ng-template" id="/tpl.html">
                Content of the template 1
           </script>
           <script type="text/ng-template" id="/tp2.html">
                Content of the template 2.
           </script>
           <script type="text/ng-template" id="/tp3.html">
                Content of the template 3.
           </script>

当我点击链接时,我可以看到模板确实被加载。我错过了什么吗?