在一个外部.html上包含角度模板

时间:2014-07-17 15:02:11

标签: javascript angularjs templates angularjs-directive

在角度中,您可以在页面中创建模板,如:

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

我想知道你是否可以把它们放在一个外部页面中,比如&#34; templates.htm&#34;,然后引用整个页面,基本上是&#34 ;在templates.htm中查看模板something.htm。&#34;

3 个答案:

答案 0 :(得分:1)

如果你不介意性能略有下降,这是我在评论中所说的一个有效例子。

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

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

$.get('templates.html').done(function (rawHtml) {
  angular.module('app').run(function ($compile) {
    $compile(rawHtml)({});
  });

  angular.element(document).ready(function () {
    angular.bootstrap(document, ['app']);
  });
});

答案 1 :(得分:0)

这不像使用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>

这是mytemplates.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>

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

答案 2 :(得分:0)

虽然从技术上讲不是你问题的直接答案,但是一个非常干净的解决方案,可能最好的表现就是使用html2js

它将使用您提供的.html模板并将它们转换为一个或多个.js文件,其中包含填充模板缓存的代码。然后,您只需包含生成的.js文件,即可完成。客户端不应该请求.html文件 - 它将首先检查缓存。

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

相关问题