javascript AngularJS 中指令函数的执行顺序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16071676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Order of execution of directive functions in AngularJS
提问by jacob
What is the order of execution of directive functions? The documentationdoesn't seem to address this.
指令函数的执行顺序是什么?该文件似乎并没有解决这个问题。
Ex
前任
- template / templateUrl (is evaluated)
- controllerFn
- compileFn
- linkFn
- template / templateUrl(已评估)
- 控制器Fn
- 编译Fn
- 链接Fn
Answer
回答
From answerbelow: http://plnkr.co/edit/79iyKSbfxgkzk2Pivuak(plunker shows nested and sibling directives)
从下面的答案:http://plnkr.co/edit/79iyKSbfxgkzk2Pivuak(plunker 显示嵌套和兄弟指令)
- Template is parsed
compile()
(changes made to the template within compile are proliferated down to linking functions)controller()
preLink()
postLink()
- 模板被解析
compile()
(在 compile 中对模板所做的更改扩展到链接函数)controller()
preLink()
postLink()
采纳答案by tamakisquare
Pre-linking function: Executed before the child elements are linked. Not safe to do DOM transformation since the compiler linking function will fail to locate the correct elements for linking.
Post-linking function: Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.
预链接功能:在链接子元素之前执行。进行 DOM 转换是不安全的,因为编译器链接函数将无法找到正确的链接元素。
后链接功能:链接子元素后执行。在 post-linking 函数中进行 DOM 转换是安全的。
Above excerpt is taken from the official docs on directives.
以上摘录取自关于指令的官方文档。
So, to answer your question, Post-linking/Link functionis when/where you can safely operate on element.children().
因此,为了回答您的问题,链接后/链接功能是您可以安全操作 element.children() 的时间/地点。
回答by Nikita
on related note, here my understanding of exec order across the DOM.
在相关说明中,这里是我对 DOM 中执行顺序的理解。
Here is a demo (open browser JS console)
Given this DOM using directive foo
:
鉴于此 DOM using 指令foo
:
<div id="1" foo>
one
<div id="1_1" foo>one.one</div>
</div>
<div id="2" foo>two</div>
...AngularJS will traverse the DOM - twice - in depth-first order:
...AngularJS 将遍历 DOM - 两次 - 以深度优先的顺序:
1st pass foo.compile()
第一遍 foo.compile()
1) compile: 1
1)编译:1
2) compile: 1_1
2)编译:1_1
3) compile: 2
3)编译:2
2nd pass: foo.controller() traversing down; foo.link() while backtracking
第二遍: foo.controller() 向下遍历;foo.link() 同时回溯
controller: 1
控制器:1
controller: 1_1
控制器:1_1
link: 1_1
链接:1_1
link: 1
链接:1
controller: 2
控制器:2
link: 2
链接:2