【发布时间】: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