Search code examples
javascriptangularjsangularjs-ng-include

AngularJS - Reusing HTML template code without AJAX call


I have an Angular app which displays "cards" (think Google cards) in two columns. Because of this I end up with HTML looking a little like

<div class="leftColumn">
    <div ng-repeat="module in Modules">
        <span>{{module.UpTime.TotalTime}}</span>

        <h2>{{module.ModuleName}}</h2>
        ...
    </div>
</div>

<div class="rightColumn">
    <!-- I want the template here too :) -->
</div>

How can I write the template code within leftColumn only once such that it can be used in both leftColumn and rightColumn. Note I realise this can be done with ng-include but why does this have to be a separate file, what if I want to specify the template within my current HTML page?


Solution

  • See documentation on how to embed multiple templates within a single page. Then just use ng-include and they will be loaded from local cache without any remote calls.


    And to make it easier, here's a code sample for you:

    <!-- include this somewhere inside the element with `ng-app` attribute ... -->
    <script type="text/ng-template" id="/tpl.html">
        <div ng-repeat="module in Modules">...</div>
    </script>
    
    <!-- ... and then use the template as you would a remote one -->
    <div class="leftColumn" ng-include="'/tpl.html'"></div>
    <div class="rightColumn" ng-include="'/tpl.html'"></div>
    

    Keep in mind that using <script> this way means compiling it as an AngularJS directive, so it must be inside the element with ng-app attribute.