Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
      }
    }
  }
  .....
like image 456
user1142130 Avatar asked Jan 27 '16 01:01

user1142130


1 Answers

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.

like image 82
bri Avatar answered Oct 17 '22 00:10

bri