What are Compile, Pre and Post linking in AngularJS?

Technology CommunityCategory: AngularJSWhat are Compile, Pre and Post linking in AngularJS?
VietMX Staff asked 3 years ago
  • Compile – This compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together. Use the compile function to change the original DOM (template element) before AngularJS creates an instance of it and before a scope is created.
  • Post-Link – This is executed after the child elements are linked. It is safe to do DOM transformation in the post- linking function. Use the post-link function to execute logic, knowing that all child elements have been compiled and all pre-link and post-link functions of child elements have been executed.
  • Pre-Link – This is executed before the child elements are linked. Not safe to do DOM transformation since the compiler linking function will fail to locate the correct elements for linking. Use the pre-link function to implement logic that runs when AngularJS has already compiled the child elements, but before any of the child element’s post-link functions have been called.
<html>
  <head>
  <title>Compile vs Link</title>
  <script src="lib/angular.js"></script>
  <script type="text/javascript">
    var app = angular.module('app', []);

    function createDirective(name) {
      return function () {
        return {
          restrict: 'E',
          compile: function (tElem, tAttrs) {
            console.log(name + ': compile');

            return {
              pre: function (scope, iElem, attrs) {
                console.log(name + ': pre link');
              },
              post: function (scope, iElem, attrs) {
                console.log(name + ': post link');
              }
            }

          }
        }
      }
    };
    app.directive('levelOne', createDirective('level-One'));
    app.directive('levelTwo', createDirective('level-Two'));
    app.directive('levelThree', createDirective('level-Three'));
  </script>
  </head>
  <body ng-app="app">
    <level-one>
      <level-two>
        <level-three>
          Hello {{name}}
        </level-three>
      </level-two>
    </level-one>
  </body>
</html>

Output:

level-One: compile
level-Two: compile
level-Three: compile
level-One: pre link
level-Two: pre link
level-Three: pre link
level-Three: post link
level-Two: post link
level-One: post link