Including angular templates on one external .html

♀尐吖头ヾ 提交于 2019-12-08 04:41:12

问题


In angular, you can create a template in the page itself like:

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

I'm wondering if you can take a bunch of these and put them together in an external page, like "templates.htm", and then reference the entire page, essentially saying "look in templates.htm for the template something.htm."


回答1:


If you don't mind a little decrease in performance, here is a working example for what I have said in the comment.

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

The key concept is to remove the np-app and bootstrap the app manually after the templates.html is loaded.

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

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



回答2:


While technically not a direct answer to your question, a very clean solution and probably best performance wise would be to use html2js.

It will take the .html templates you give it and turn them into one or more .js files containing code that fills the template cache. Then you just include the generated .js file and you're done. The client should not request the .html files - it will check the cache first.

It does require some changes to your build setup but can be fully automated.




回答3:


Isn't this as simple as using an ng-include ?

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

(mind the single quotes with src)

@Aaron: Adding more information on what i did. Here is the body of my index.html ( the main page)

      <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>

And here is the 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>

When i click the links i can see that the templates do get loaded. Am i missing something ?



来源:https://stackoverflow.com/questions/24807121/including-angular-templates-on-one-external-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!