2.compiler 我们清楚的看到angularjs的官方文档上边都是驼峰式命名法,譬如ngApp、ngModule、ngBind等等这些都是相关的指令,其中html compiler就是允许我们自己定义元素 属性和标签,Angular将这些附加行为称为directives。 官方文档对compiler的解释是这样的 复制代码 代码如下: Compiler Compiler is an Angular service which traverses the DOM looking for attributes. The compilation process happens in two phases. Compile: traverse the DOM and collect all of the directives. The result is a linking function. Link: combine the directives with a scope and produce a live view. Any changes in the scope model are reflected in the view, and any user interactions with the view are reflected in the scope model. This makes the scope model the single source of truth. Some directives such as ng-repeat clone DOM elements once for each item in a collection. Having a compile and link phase improves performance since the cloned template only needs to be compiled once, and then linked once for each clone instance.
2.编译的步骤 HTML“编译”的三个步骤: 1. 首先,通过浏览器的标准API,将HTML转换为DOM对象。这是很重要的一步。因为模版必须是可解析(符合规范)的HTML。这里可以跟大多数的模版系统做对比,它们一般是基于字符串的,而不是基于DOM元素的。 2. 对DOM的编译(compilation)是通过调用$comple()方法完成的。这个方法遍历DOM,对directive进行匹配。如果匹配成功,那么它将与对应的DOM一起,加入到directive列表中。只要所有与指定DOM关联的directive被识别出来,他们将按照优先级排序,并按照这个顺序执行他们的compile() 函数。directive的编译函数(compile function),拥有一个修改DOM结构的机会,并负责产生link() function的解析。$compile()方法返回一个组合的linking function,是所有directive自身的compile function返回的linking function的集合。 3. 通过上一步返回的linking function,将模版与scope连接起来。这反过来会调用directive自身的linking function,允许它们在元素上注册一些监听器(listener),以及与scope一起建立一些watches。这样得出的结果,是在scope与DOM之间的一个双向、即时的绑定。scope发生改变时,DOM会得到对应的响应。 复制代码 代码如下: var $compile = ...; // injected into your code var scope = ...; var html = "<div ng-bind="exp"></div>"; // Step 1: parse HTML into DOM element var template = angular.element(html); // Step 2: compile the template var linkFn = $compile(template); // Step 3: link the compiled template with the scope. linkFn(scope);