Developer Guide: Angular HTML Compiler: Understanding How the Compiler Works

Work in Progress This page is currently being revised. It might be incomplete or contain inaccuracies.

Every widget, directive and markup is defined with a compile function, which the angular compiler executes on each widget or directive it encounters. The compile function optionally returns a link function. This compilation process happens automatically when the page is loaded when you specify ng:autobind in the script tag from which you load the angular script file. (See Initializing Angular.)

The compile and link functions are related as follows:

Note that angular's built-in widgets, directives, and markup have predefined compile and link functions that you don't need to modify. When you create your own widgets, directives, or markup, you must write compile and link functions for them. Refer to the Compiler API for details.

When the angular compiler compiles a page, it proceeds through 3 phases: Compile, Create Root Scope, and Link:

  1. Compile Phase

    1. Recursively traverse the DOM, depth-first.
    2. Look for a matching compile function of type widget, then markup, then directive.
    3. If a compile function is found then execute it.
    4. When the compile function completes, it should return a link function. Aggregate this link function with all link functions returned previously by step 3.
    5. Repeat steps 3 and 4 for all compile functions found.

The result of the compilation phase is an aggregate link function, which comprises all of the individual link functions.

  1. Create Root Scope Phase

  2. Inject all services into the root scope.

  3. Link Phase

    1. Execute the aggregate link function with the root scope. The aggregate link function calls all of the individual link functions that were generated in the compile phase.
    2. If there are any clones of the DOM caused by repeating elements, call the link function multiple times, one for each repeating item.

Note that while the compile function is executed exactly once, the link function can be executed multiple times, for example, once for each iteration in a repeater.

The angular compiler exposes methods that you will need to make use of when writing your own widgets and directives. For information on these methods, see the Compiler API doc.

Related Topics

Related API