这实际上意味着在这里完成的 DOM 操作将运行一次,并始终传播。
运行一次?
这是指AngularJS的编译过程。当 AngularJS 编译器遍历 DOM 时,它将只编译一次找到的指令。
DOM 操作?
当调用指令的编译函数时,有机会在 AngularJS 编译器之前修改 HTML。
总是传播?
这只是意味着最终的 DOM 是在编译过程结束时确定的。
例子
要想明白这一点,请考虑以下示例:
<div directive1> <!-- grandparent -->
<div directive2> <!-- parent -->
<div directive3> <!-- child -->
</div>
</div>
</div>
AngularJS 编译器将首先访问祖父母,然后是父母,最后是孩子。
在 Angular 编译之前有三种修改 HTML 的机会:
- 指令1编译函数
- 指令2编译函数
- 指令3编译函数
现在考虑当我们在指令 1 的 compile 函数中操作 DOM 时最终的 HTML 是如何变化的:
当directive1的编译函数被调用时:
<div directive1> <!-- compiled -->
<div directive2> <!-- not compiled -->
<div directive3> <!-- not compiled -->
</div>
</div>
</div>
在 compile 函数中,让我们在 AngularJS 编译器之前更改 HTML:
app.directive('directive1', function() {
restrict: 'A',
compile: function($element, $attr) {
// $element points to directive1 element
$element.html('<div directive4></div>');
}
});
调用directive1的编译函数后:
<div directive1> <!-- compiled -->
<div directive4> <!-- not compiled -->
</div>
</div>
注意 DOM 是如何变化的,因此指令 2 和指令 3 不再存在,指令 4 是下一个要编译的行。
预链接提供了轻微的性能提升,因为当父级修改预链接中的范围时,它们可以防止内部指令运行第二个摘要循环
唔。这对我来说毫无意义。据我了解,摘要阶段发生在链接前和链接后阶段之后。我不确定在链接前或链接后阶段修改范围将如何影响摘要周期。
本文引用了以下图片:
http ://www.toptal.com/angular-js/angular-js-demystifying-directives
