11

From the doc of angularjs, when defining a directive, there's a postLink in compile, and a postLink in link

myModule.directive('directiveName', function factory(injectables) {
  var directiveDefinitionObject = {
    priority: 0,
    template: '<div></div>',
    templateUrl: 'directive.html',
    replace: false,
    transclude: false,
    restrict: 'A',
    scope: false,
    compile: function compile(tElement, tAttrs, transclude) {
      return {
        pre: function preLink(scope, iElement, iAttrs, controller) { ... },
        post: function postLink(scope, iElement, iAttrs, controller) { ... }
      }
    },
    link: function postLink(scope, iElement, iAttrs) { ... }
  };
  return directiveDefinitionObject;
});

What's the difference between them? I notice the postLink in link has a argument less than the one in compile. And are there any other difference?

Freewind
  • 193,756
  • 157
  • 432
  • 708

2 Answers2

30

They're no different, what you have there is just psuedo-code from the documentation. The postLink function is just the most important one, so there are a variety of ways to declare it.

Here is a Plunker as an example...

... and here is some psuedo code showing the different declarations of a postLink function:

app.directive('dir1', function () {
   return function(scope, elem, attr) {
       //this is the same
   };
});

app.directive('dir2', function () {
   return {
       link: function(scope, elem, attr) {
           //this is the same
       }
   };
});

app.directive('dir3', function () {
   return {
      compile: function compile(tElement, tAttrs, transclude) {
         return {
           post: function postLink(scope, elem, attrs) {
              //this is the same
           }
         }
      }
   };
});

... you only need one.

Ben Lesh
  • 107,825
  • 47
  • 247
  • 232
0

The essential difference is that the in the pre-link function, the child elements have not been linked yet. But in the post-link function, it has.

This has implications for DOM manipulation. Since the process of linking may further manipulate the DOM, it is only safe for the directive to manipulate the DOM when its children have already been linked - and this is only true in the post-link function.

Michael Kang
  • 52,003
  • 16
  • 103
  • 135