$区别编译和对角指令编译功能? [英] Difference between $compile and the compile function on a directive in Angular?

查看:140
本文介绍了$区别编译和对角指令编译功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用我建立了一个资料库,返回解析为模板的内容的承诺找回我的指令模板。

I am trying to retrieve my template for a directive using a repository I have built that returns a promise that resolves to the contents of the template.

是什么在指令使用编译的功能和使用 $编译服务之间的差异链接功能?

What is the difference between using the compile function in a directive and using the $compile service in the link function?

编译功能

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

此呈现HTML,但范围并不绑定到DOM元素

This renders the HTML, but the scope is not bound to the DOM elements.

使用$编译

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

这正常工作。

有什么区别吗?

推荐答案

$编译

编译HTML字符串或DOM成模板,并产生一个模板
  功能,然后可以用于链接的范围和​​模板
  在一起。

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.

汇编是走DOM树和匹配DOM的过程
  元素的指令。

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

所以 $编译做任何对DOM元素都交给它的角处理。

So $compile does the Angular processing on whatever DOM elements are handed to it.

$编译都发现指令中的编译功能运行。请注意,每个指令的编译功能是执行只有一次,不管该指令有多少实例存在。

During $compile the Compile Function within all found directives is run. Note that each directive's compile function is executed just once, no matter how many instances of that directive there are.

在由 $制作的模板函数编译执行(链接范围和模板一起),则执行的每个指令的链接功能(在传递的范围作为第一个参数)。

When the template function produced by $compile is executed ("to link scope and the template together") then each directive's link function is executed (with the scope passed in as the first parameter).

所以 $编译变换DOM。而该指令的编译功能是什么运行,该指令,这一转变过程中。

So $compile transforms the DOM. While the directive's compile function is what's run, for that directive, during that transformation.

这里有一个小小提琴你可以尝试用它显示执行的顺序。

Here's a little fiddle you can experiment with which shows the order of execution.

这篇关于$区别编译和对角指令编译功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆