How Directives are compiled?

Technology CommunityCategory: AngularJSHow Directives are compiled?
VietMX Staff asked 3 years ago

It is important to note that Angular operates on DOM nodes rather than strings. Usually, you don’t notice this because when an html page loads, the web browser parses HTML into the DOM automatically. HTML compilation happens in three phases:

  1. The $compile traverses the DOM and looks for directives. For each directive it finds, it adds it to a list of directives.
  2. Once the entire DOM has been traversed, it will sort that list of directives by their priority. Then, each directive’s own compile function is executed, giving each directive the chance to modify the DOM itself. Each compile function returns a linking function, which is then composed into a combined linking function and returned.
  3. $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 individual directives, registering listeners on the elements and setting up $watch with the scope as each directive is configured to do.

The pseudo code for the above process is given below:

var $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);