Angular directives – when and how to use compile, controller, pre-link and post-link [closed]

When writing an Angular directive, one can use any of the following functions to manipulate the DOM behaviour, contents and look of the element on which the directive is declared:

  • compile
  • controller
  • pre-link
  • post-link

There seem to be some confusion as for which function should one use. This question covers:

Directive basics

  • How to declare the various functions?
  • What is the difference between a source template and an instance template?
  • In which order the directive functions are executed?
  • What else happens between these function calls?

Function nature, do’s and dont’s

  • Compile
  • Controller
  • Pre-link
  • Post-link

Related questions:

  • Directive: link vs compile vs controller.
  • Difference between the ‘controller’, ‘link’ and ‘compile’ functions when defining an angular.js directive.
  • What is the difference between compile and link function in angularjs.
  • Difference between the pre-compile and post-compile element in AngularJS directives?.
  • Angular JS Directive – Template, compile or link?.
  • post link vs pre link in Angular js directives.

8 Answers
8

Leave a Comment