26

As outlined here:

http://docs.angularjs.org/guide/directive

Angular js directives take two different types of link functions:

Pre-linking function 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.

Post-linking function Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.

Additionally, it appears that the default key of link will bind to postLink if given an anonymous function.

When and why would I ever want to use a pre link function?

Abraham P
  • 15,029
  • 13
  • 58
  • 126
  • 2
    Please see this http://stackoverflow.com/questions/15297797/when-shall-we-use-prelink-of-directives-compile-function – Chandermani Aug 18 '13 at 10:32
  • Perhaps a more comprehensive overview of directive functions: [Angular directives - when to use compile, controller, pre-link and post-link](http://stackoverflow.com/questions/24615103). – Izhaki Jul 07 '14 at 16:41
  • 1
    http://odetocode.com/blogs/scott/archive/2014/05/28/compile-pre-and-post-linking-in-angularjs.aspx – zloctb Aug 22 '16 at 07:33

1 Answers1

21

The only time you'd want to use a pre link is when you need to perform some preparation on the scope before any child elements compile.

My team has used it when writing a grid directive to define the grid object on the scope and setup some of its properties that are needed before any of the child row and cell objects are compiled.

Hope that helps!

thechrisman
  • 360
  • 3
  • 3
  • 7
    I'm not sure this is accurate. Compilation phase is over by the time pre-link / post-link phase runs. – Michael Kang Apr 09 '15 at 10:48
  • 3
    The more accurate answer might be that you use pre if you need to do some setup before any child does any other setup. post link runs in opposite 'order'. http://www.jvandemo.com/the-nitty-gritty-of-compile-and-link-functions-inside-angularjs-directives/ – Gjermund Bjaanes May 20 '15 at 14:28
  • This should not be the accepted answer, @pixelbits is correct in stating that the child elements are already compiled before the pre-link of any parent. – Abhishek Jain Jan 20 '18 at 09:26
  • 1
    Pls refer [to this answer](https://stackoverflow.com/a/16277768/4007775) instead. – Abhishek Jain Jan 20 '18 at 09:32