gpt4 book ai didi

angularjs - $compile 和 Angular 指令上的编译函数之间的区别?

转载 作者:行者123 更新时间:2023-12-02 23:50:56 26 4
gpt4 key购买 nike

我正在尝试使用我构建的存储库检索指令模板,该存储库返回解析为模板内容的 promise 。

在指令中使用 compile 函数与在 link 函数中使用 $compile 服务有什么区别?

编译函数

compile: function (element, attrs) {
templateRepository.get('Shared/Login').then(function (result) {
element.replaceWith(result);
});
}

这会呈现 HTML,但范围不会绑定(bind)到 DOM 元素。

使用 $compile

link: function (scope, elem, attrs) {
templateRepository.get('Shared/Login').then(function (result) {
elem.html(result);
$compile(elem.contents())(scope);
});
}

这按预期工作。

这里有什么区别?

最佳答案

$compile :

Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.

The compilation is a process of walking the DOM tree and matching DOM elements to directives.

因此,$compile会对传递给它的任何 DOM 元素进行 Angular 处理。

$compile期间,所有找到的指令中的编译函数都会运行。请注意,每个指令的编译函数仅执行一次,无论该指令有多少个实例。

当执行 $compile 生成的模板函数(“将范围和模板链接在一起”)时,将执行每个指令的链接函数(将范围作为第一个参数传入)。

所以 $compile 转换 DOM。虽然指令的编译函数是在转换期间针对该指令运行的函数。

这里有一点fiddle你可以尝试一下它显示的执行顺序。

关于angularjs - $compile 和 Angular 指令上的编译函数之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21197073/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com