Heim > Fragen und Antworten > Hauptteil
首先说的当下的技术环境:angular1.6,ui-route,require,疑问:
1、ui-route加载的template和动态注册的controller谁先被编译执行?例如:我想获取template的#id的宽必须要$timeout?否则就出现undefine
2、自定义指令的compile是不是先于template加载?还是并行加载?
有点混乱,跪求解答,相关文章和解惑也跪谢!
附加题:{{}}会自动将类型转化为字符串吧?
谢谢,回答部分也非常感谢
淡淡烟草味2017-05-15 17:13:14
官方有详细解释,关于编译过程的介绍:
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的文章.
PHP中文网2017-05-15 17:13:14
我认为的顺序应该是这样的:加载template同时走controller,在controller里初始化数据,然后进入$digest阶段来render template。所以controller加载过程中你获取template的#id的宽就有可能得不到。
写一个$timeout,会在$digest结束后执行timeout里面的代码,并再次触发一次$digest.
自定义指令的compile阶段其实是确定template的结构,compile阶段可以更改template的结构,link阶段就是准备数据,然后render template。
如有不对,欢迎指正讨论。