$compile traverses the DOM and matches directives.
If the compiler finds that an element matches a directive, then the directive is added to the list of directives that match the DOM element.A single element may match multiple directives.
Once all directives matching a DOM element have been identified, the compiler sorts the directives by their priority.
Each directive's compile functions are executed. Each compile function has a chance to modify the DOM. Each compile function returns a link function. These functions are composed into a "combined" link function, which invokes each directive's returned link function.
$compile links the template with the scope by calling the combined linking function from the previous step. This in turn will call the linking function of the inpidual directives, registering listeners on the elements and setting up $watchs with the scope as each directive is configured to do.
The result of this is a live binding between the scope and the DOM. So at this point, a change in a model on the compiled scope will be reflected in the DOM.
官方有详细解释,关于编译过程的介绍:
HTML compilation happens in three phases:
$compile traverses the DOM and matches directives.
If the compiler finds that an element matches a directive, then the
directive is added to the list of directives that match the DOM
element.A single element may match multiple directives.
Once all directives matching a DOM element have been identified, the
compiler sorts the directives by their priority.
Each directive's compile functions are executed. Each compile
function has a chance to modify the DOM. Each compile function
returns a link function. These functions are composed into a
"combined" link function, which invokes each directive's returned
link function.
$compile links the template with the scope by calling the combined
linking function from the previous step. This in turn will call the
linking function of the inpidual directives, registering listeners
on the elements and setting up $watchs with the scope as each
directive is configured to do.
The result of this is a live binding between the scope and the DOM. So at this point, a change in a model on the compiled scope will be reflected in the DOM.
具体请题主详读 https://docs.angularjs.org/gu... 这篇关于compiler的文章.
我认为的顺序应该是这样的:加载template同时走controller,在controller里初始化数据,然后进入$digest阶段来render template。所以controller加载过程中你获取template的#id的宽就有可能得不到。
写一个$timeout,会在$digest结束后执行timeout里面的代码,并再次触发一次$digest.
自定义指令的compile阶段其实是确定template的结构,compile阶段可以更改template的结构,link阶段就是准备数据,然后render template。
如有不对,欢迎指正讨论。