angular.js - angularjs的加载编译机制

【字号: 日期:2022-12-24浏览:35作者:雯心

问题描述

首先说的当下的技术环境:angular1.6,ui-route,require,疑问:1、ui-route加载的template和动态注册的controller谁先被编译执行?例如:我想获取template的#id的宽必须要$timeout?否则就出现undefine2、自定义指令的compile是不是先于template加载?还是并行加载?有点混乱,跪求解答,相关文章和解惑也跪谢!附加题:{{}}会自动将类型转化为字符串吧?谢谢,回答部分也非常感谢

问题解答

回答1:

官方有详细解释,关于编译过程的介绍:

HTML compilation happens in three phases:

$compile traverses the DOM and matches directives.

If the compiler finds that an element matches a directive, then thedirective is added to the list of directives that match the DOMelement.A single element may match multiple directives.

Once all directives matching a DOM element have been identified, thecompiler sorts the directives by their priority.

Each directive’s compile functions are executed. Each compilefunction has a chance to modify the DOM. Each compile functionreturns a link function. These functions are composed into a'combined' link function, which invokes each directive’s returnedlink function.

$compile links the template with the scope by calling the combinedlinking function from the previous step. This in turn will call thelinking function of the inpidual directives, registering listenerson the elements and setting up $watchs with the scope as eachdirective 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的文章.

回答2:

我认为的顺序应该是这样的:加载template同时走controller,在controller里初始化数据,然后进入$digest阶段来render template。所以controller加载过程中你获取template的#id的宽就有可能得不到。写一个$timeout,会在$digest结束后执行timeout里面的代码,并再次触发一次$digest.

自定义指令的compile阶段其实是确定template的结构,compile阶段可以更改template的结构,link阶段就是准备数据,然后render template。

如有不对,欢迎指正讨论。

相关文章: