What's the difference between the 2 "postLink" functions in directive?

10,663

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.

Share:
10,663
Freewind
Author by

Freewind

A programmer ([email protected])

Updated on June 27, 2022

Comments

  • Freewind
    Freewind about 2 years

    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?