简体   繁体   English

AngularJS-在没有AJAX调用的情况下重用HTML模板代码

[英]AngularJS - Reusing HTML template code without AJAX call

I have an Angular app which displays "cards" (think Google cards) in two columns. 我有一个Angular应用程序,该应用程序在两列中显示“卡片”(例如Google卡片)。 Because of this I end up with HTML looking a little like 因此,我最终得到的HTML看起来像

<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 . 我如何只在leftColumnleftColumn一次模板代码,以便可以在leftColumnrightColumn使用它。 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? 注意,我意识到这可以使用ng-include来完成,但是为什么必须将其作为单独的文件,如果我想在当前HTML页面中指定模板呢?

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. 然后只需使用ng-include ,它们将从本地缓存加载,而无需任何远程调用。


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 . 请记住,以这种方式使用<script>意味着将其编译为AngularJS指令,因此它必须位于ng-app属性的元素ng-app

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM