user1142130
user1142130

Reputation: 1645

In Angular: are the compile function's pre and post methods the same as link's pre and post

In an angular directive's compile function there is a pre and post. Is this pre and post really the same as the link function?

For example in the code below, is the link function the same (shortcut if you will) as the pre and post of the compile function below it?

Link

....
link: {
  pre: function(scope, elem, attr) {
   //stuff
  },
  post: function(scope, elem, attr) {
  //stuff
  }    
}
....

Compile...

  ....
  compile: function(tElem, tAttrs){
    return {
      pre: function(scope, iElem, iAttrs){
      //stuff
      },
      post: function(scope, iElem, iAttrs){
      //stuff
      }
    }
  }
  .....

Upvotes: 11

Views: 276

Answers (2)

georgeawg
georgeawg

Reputation: 48968

When this overloading happens, are you aware of anything different happening (i.e. any other functionality being added) as supposed to just returning pre and post from compile?

If you look at the source code, when the $directiveProvider registers the directives, if the compile property is missing and the link property exists, it creates a compile property that is an empty function that returns the link property.

So the answer is that the link functions returned by the compile function are the same as the link functions provided by the link property of the DDO. No other functionality is added.

Upvotes: 0

bri
bri

Reputation: 3030

Compile is run first (and is usually where you maipulate your "template" dom elements). Link is run second, and is usually where you attach your directive to $scope.

They also run in a specific order, so you can use that fact when you're designing directives that require some "parent" directive setup in order to operate properly (like a tr:td sorta thing).

There's a really great article on timing for compile vs link you can take a look at for more clarity.

Also - there's a very low level stack answer to a similar question you might like (note that its NOT the one listed first, it's the one most upvoted).

So, What's the Difference?

So are compile pre/post link "the same" as the link function? You decide.

If you define compile on a directive, the framework ignores your link function (because the compile function is supposed to return pre/post link functions).

It's a little bit like link overloads compile.postLink and link.pre overloads compile.preLink.

Upvotes: 8

Related Questions