【发布时间】:2013-05-23 19:27:54
【问题描述】:
我想先编译一个角度指令来附加属性,然后再将代码编译为其他指令。无论如何我可以使用 compile: pre post 或其他东西来编译这个
属性附加 至 指示 至 父指令模板?
【问题讨论】:
标签: angularjs hyperlink compilation directive
我想先编译一个角度指令来附加属性,然后再将代码编译为其他指令。无论如何我可以使用 compile: pre post 或其他东西来编译这个
属性附加 至 指示 至 父指令模板?
【问题讨论】:
标签: angularjs hyperlink compilation directive
假设您有一个指令<foo></foo> (restrict: 'E')。您想要动态添加属性(~ 修改原始 DOM,而不是模板),这应该在指令的 $compile 步骤中完成。添加属性后,要让 angularjs 意识到是否有可以触发的新指令,您必须编译新元素。例如,这就是 ng-include 所做的。它包含 DOM 中的元素并编译它们以便可以使用新的指令。
指令foo:
compile: function ($tElement, $tAttrs) {
var el = $tElement[0];
el.setAttribute('bar', 'newFancyValue');
return function (scope, element, attrs) {
// you can even append html elements here, for example the template
element.append("<book></book>");
$compile(element)(scope);
};
}
指令bar(带有restrict: 'A')可以有任何你想要的代码。
这是一个您可能也想阅读的相关问题A general directive with a specific type (UI components inheritance)
查看文档中的 transclude 函数,了解如何在 book 中添加 foo 之前的内部元素
【讨论】:
$tElement的第一个参数是一个数组而不是一个元素,因此需要var el = $tElement[0];。大多数示例将其视为单个对象,但与 OP 一样,我得到一个数组。