【问题标题】:How to include template within a directive template?如何在指令模板中包含模板?
【发布时间】:2015-09-13 13:22:29
【问题描述】:

如何在 Angular 指令的模板中包含 .html 模板?

我当前包含模板的方式成功地将模板的 HTML 拉入指令模板,但模板中的变量没有链接到控制器。

这是我目前正在做的:

_directive_template.html

<section>
  ...
 <div ng-include="'/templates/_template_to_be_included.html'"></div>
  ...
</section> 

_template_to_be_included.html

 <form>
    <input ng-model="some_value">
    <button type="submit">Update</button>
 </form>

指令

...
function link(scope, element, attrs) {
      scope.some_value  // not correctly linking to some_value within included template 
      }
  return {
    scope: {},
    link: link,
    templateUrl: '/templates/_directive_template.html'
  };
....

当我将 _template_to_be_included.html 的 HTML 复制并直接粘贴到指令模板中(而不是像上面那样使用 ng-include)时,一切正常,some_value 在表单中的位置和在表单中的位置之间正确链接控制器。

如何正确地将模板包含到指令模板中,并将其变量链接到指令中的对应部分?似乎 ng-include 应该可以工作,因为它会“获取并编译”指定的模板...

Plunkr: 输入一些输入并点击“更新”

【问题讨论】:

  • 它应该可以工作.. 你能创建一个 plunker
  • 在指令定义中使用 templateURL 属性是标准方式
  • 你是说你在模板标记中嵌入了 ng-include 吗?类似:模板:
    ?如果是这样,我想知道您是否遇到时间问题 - 即它在 ng-include 完成之前编译指令。就像@entre 说的那样,很高兴见到一个笨蛋。
  • @user1821052 我已经在使用 templateUrl 将模板 (_directive_template.html) 绑定到我的指令。问题是_directive_template.html 需要包含另一个模板。 @你的第二条评论:是的,这就是我的意思。更新了我的 Q 以澄清。我会在 plunkr 上工作。
  • 如果你使用模板而不是templateUrl会发生什么?因此,将标记与 ng-include 一起嵌入。由于 templateUrl 和 ng-include 都执行 $http 请求,因此 templateUrl 可能在 ng-include 之前完成(并编译)?

标签: javascript angularjs templates angularjs-directive angularjs-ng-include


【解决方案1】:

我相信我理解了这个问题。我组装了一个 Plunker。

http://plnkr.co/edit/L4ZN5XhOpex6U5MRKsZ4?p=preview

<div>
  <h1>Directive Template</h1>
  <p>This is just some garbage text.</p>

  <h1>ng-include template</h1>
  <div ng-include="'_template_to_be_included.html'"></div>
</div>

【讨论】:

  • 谢谢。这实际上触及了我的问题的核心:plnkr.co/edit/D0HjA4lbTtL0zrnWqQGA?p=preview Some_value 在提交时在函数中使用时返回未定义
  • 给我一点,我会更新 plunker 来帮助你解决你的问题。
  • 延迟响应,但以防万一你仍然需要它:你失去了 ng-init 的范围。用 alert(this.some_value) 改变你的 alert(scope.some_value) 就可以了
猜你喜欢
  • 1970-01-01
  • 2012-11-18
  • 2015-09-05
  • 1970-01-01
  • 1970-01-01
  • 2016-06-02
  • 1970-01-01
  • 2012-08-15
  • 2011-11-16
相关资源
最近更新 更多