【问题标题】:Why it did NOT include <sciprt><script> within a html when I import this html as angularjs directive?当我将此 html 作为 angularjs 指令导入时,为什么它没有在 html 中包含 <script><script> ?
【发布时间】:2017-10-27 12:59:46
【问题描述】:

我尝试了一段时间,但没有运气。

我正在使用 angularjs。我正在使用@templateCache。 https://docs.angularjs.org/api/ng/service/$templateCache

假设我有一个命名为 'foo' 的 angularjs 指令,该指令的模板是 'foo.html'。在这个'foo.html'中,我有以下代码:

<h1>Below script is for template cache purpose</h1>
<script type="text/ng-template" id="templateId.html">
  <p>This is the content of the template</p>
</script>

在我的另一个 HTML 中,假设为“bar.html”。在这个html中,我有&lt;foo&gt;&lt;/foo&gt;,它只加载&lt;h1&gt;Below script is for template cache purpose&lt;/h1&gt;,但是当我检查$templateCache.get('foo.html')时,它没有这个'foo.html'。

尝试了很多方法后,我不知道如何解决我的问题。

附:如果我

<script type="text/ng-template" id="templateId.html">
      <p>This is the content of the template</p>
    </script>

直接在“bar.html”中。 $templateCache.get('foo.html') 可以获取 'foo.html'。但我不想直接放入'bar.html',因为我有很多,我想在单独的文件中保持干净,也不要破坏当前代码。

补充问题:如果&lt;foo&gt;&lt;/foo&gt; 在我的'bar.html' 中有效,我不想让'foo.html' 的&lt;h1&gt;&lt;/h1&gt; 出现在'bar.html' 中。我让&lt;foo ng-if = "false"&gt;&lt;/foo&gt; 在'bar.html' 中吗?还是有其他方法可以做到这一点?将所有 &lt;script&gt;&lt;/script&gt; 添加到一个新的 'script.js' 文件中,并让 &lt;script src="script.js"&gt;&lt;/script&gt; 在 'foo.html' 和 'bar.html' 中?

【问题讨论】:

  • 所以,问题是为什么它包含&lt;script&gt; 或不包含&lt;script&gt; - 你的标题暗示它did,你的问题暗示它didn 't
  • 抱歉,我的标题有错字。它没。我修正了标题。

标签: javascript html angularjs angular-templatecache


【解决方案1】:

当 Angular 在脚本标签中看到类型 text/ng-template 时,就会执行编译函数。来自角度来源:

var scriptDirective = ['$templateCache', function($templateCache) {
  return {
    restrict: 'E',
    terminal: true,
    compile: function(element, attr) {
      if (attr.type === 'text/ng-template') {
        var templateUrl = attr.id,
            text = element[0].text;

        $templateCache.put(templateUrl, text);        
      }
    }
  };
}];

此编译函数获取 id 属性并调用 $templateCache.put(idTemplate,template)。

所以要让 bar 指令获取 $templateCache.get(idOfYourTemplate) 的内容,他必须在 foo 中的 script 标签被评估后调用。

如果 foo 标签在 bar 的 html 中,则 bar 控制器/链接函数将首先被评估,而不是 foo 中脚本标签的评估。

为了帮助您解决第二个问题,您可以将参数传递给您的 foo 指令以隐藏 h1 内容。你可以这样做:

(功能() { '使用严格'; 有角度的 .module('app') .directive('foo', foo); foo.$inject = []; 函数 foo() { // 用法: // // 创建: // 变量 foo = { 绑定控制器:真, 控制器:FooController, 控制器作为:'vm', 链接:链接, 限制:'E', templateUrl: 'directives/foo.html', 范围: { 隐藏标题:'=' } }; 返回富; 功能链接(范围,元素,属性){ } } /* @ngInject */ 函数 FooController () { } })();

scope 属性指定你的指令和外部世界之间的接口。等号“=”用于以双向数据绑定接收值。

并且在您的模板中,您将放置一个 ng-if 以使用参数值来限制渲染:

<h1 ng-if="vm.hideTitle">Below script is for template cache purpose</h1>
<script type="text/ng-template" id="templateId1.html">
  <p>This is the content of the template</p>
</script> 

关于您的第三个问题,如果我理解正确,您可以将所有脚本放在一个唯一的文件 script.js 中,并拥有 Angular 提供给您的所有东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-03
    • 2020-10-01
    • 1970-01-01
    • 2011-05-23
    • 2016-08-02
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多