【问题标题】:AngularJS - Reusing HTML template code without AJAX callAngularJS - 在没有 AJAX 调用的情况下重用 HTML 模板代码
【发布时间】:2014-11-25 10:59:30
【问题描述】:

我有一个 Angular 应用程序,它在两列中显示“卡片”(想想 Google 卡片)。因此,我最终得到的 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>

我怎样才能在leftColumn 中只编写一次模板代码,以便它可以在leftColumnrightColumn 中使用。注意我意识到这可以通过ng-include 完成,但是为什么这必须是一个单独的文件,如果我想在我当前的 HTML 页面中指定模板呢?

【问题讨论】:

标签: javascript angularjs angularjs-ng-include


【解决方案1】:

See documentation 了解如何在单个页面中嵌入多个模板。然后只需使用ng-include,它们将从本地缓存加载,无需任何远程调用。


为了方便起见,这里有一个code sample 给你:

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

请记住,以这种方式使用&lt;script&gt;意味着将其编译为AngularJS指令,因此它必须位于具有ng-app属性的元素内

【讨论】:

  • 我不想通过外部 HTML 页面包含它!
  • 您是否阅读了我的回答部分,其中说“在单个页面中包含多个模板”? (那我把它改成 "embed"。)你看过链接的文档了吗?
  • 如何在没有点击的情况下做到这一点?我试图让它静态工作但它不玩球,它一直试图加载/tpl.html - 我复制了你的代码,但它仍然这样做
  • working demo。你的 &lt;script type="text/ng-template"&gt; 是一个 AngularJS 指令,所以它不能在你的 ng-app 元素之外。
猜你喜欢
  • 1970-01-01
  • 2018-06-20
  • 2012-05-03
  • 1970-01-01
  • 1970-01-01
  • 2018-05-21
  • 2011-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多