Skip to content

Instantly share code, notes, and snippets.

@simonwoo
Created September 26, 2016 14:20
Show Gist options
  • Select an option

  • Save simonwoo/e148dec25d8cb5a141e6279ce3a99cfc to your computer and use it in GitHub Desktop.

Select an option

Save simonwoo/e148dec25d8cb5a141e6279ce3a99cfc to your computer and use it in GitHub Desktop.

渲染是针对directive来讲的,angularJS内置了很多directive,我们也可以之定义directive,这些directive最终都是通过 $compile service来完成渲染工作的。

$compile service主要分为两个阶段:compile 和 link。

  • 首先$compile会遍历DOM,收集所有的directive,如果同一element有多个directive,那么会根据piroirty来排优先级。
  • 调用所有的directive的compile函数,每个directive的compile会返回一个link函数(包含当前的scope),将这些link函数组合成一个函数fnLink。
  • 在link阶段,将$rootScope传递给fnLink(这时angular会将相应module data添加到$watch list),执行生成View。

可以通过一下代码理解:

normalvar $compile = ...; // injected into your code
var scope = ...;
var parent = ...; // DOM element where the compiled template can be appended

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.
var element = linkFn(scope);

// Step 4: Append to DOM (optional)
parent.appendChild(element);
normal
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment