Explain the compilation process of AngularJS?

Angular’s HTML compiler allows us to teach the browser, new HTML syntax. It also allows the developer to attach new behavior or attributes to any HTML element known as directives. AngularJS compilation process automatically takes place in the web browser. It does not contain any server-side or pre-compilation procedure.

AngularJS uses <$compiler> service for the compilation process of an Angular HTML page. Its compilation process starts after the HTML page (static DOM) is completely loaded.

It occurs in two phases:

  • Compile
    It checks into the entire DOM and collects all of the directives.
  • Link
    It connects the directives with a scope and produces a live view.
    The concept of compile and link has been added from C language. The code is compiled and then linked.
    1. Template Compilation:
      • HTML Compilation: AngularJS processes the HTML markup to identify Angular-specific elements and directives. It uses a directive called ng-app to define the root of the Angular application.
      • Template Parsing: AngularJS parses the HTML templates and extracts the directives and expressions. It creates a template function for each template, which is later used to instantiate the view.
    2. Linking Phase:
      • Scope Creation: AngularJS creates a scope for each controller and directive. A scope is an object that refers to the application model and acts as a bridge between the controller and the view.
      • Compile and Link Functions: AngularJS generates compile and link functions for each directive. The compile function is responsible for template transformation, and the link function is responsible for linking the template to the scope.
      • DOM Manipulation: During the linking phase, AngularJS manipulates the DOM based on the directives and expressions in the template. It establishes the connection between the view and the underlying data model.
    3. Runtime:
      • Digest Cycle: AngularJS introduces a concept called the “digest cycle.” During the digest cycle, AngularJS compares the current state of the model with the previous one, updating the view if any changes are detected. This process ensures that the view is always in sync with the model.

    In summary, AngularJS compiles HTML templates, creates scopes, generates compile and link functions for directives, and then links the templates to the scopes during the runtime, ensuring a dynamic and data-bound web application. Keep in mind that AngularJS is an older version of Angular, and newer versions of Angular (such as Angular 2 and later) have significantly different architectures