Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of execution of directive functions in AngularJS

What is the order of execution of directive functions? The documentation doesn't seem to address this.

Ex

  1. template / templateUrl (is evaluated)
  2. controllerFn
  3. compileFn
  4. linkFn

Answer

From answer below: http://plnkr.co/edit/79iyKSbfxgkzk2Pivuak (plunker shows nested and sibling directives)

  1. Template is parsed
  2. compile() (changes made to the template within compile are proliferated down to linking functions)
  3. controller()
  4. preLink()
  5. postLink()
like image 468
Jakob Jingleheimer Avatar asked Apr 17 '13 22:04

Jakob Jingleheimer


People also ask

How does directive work in AngularJS?

AngularJS directives are extended HTML attributes with the prefix ng- . The ng-app directive initializes an AngularJS application. The ng-init directive initializes application data. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

How many types of directives are there in AngularJS?

There are two types of AngularJs directives: Built-in directive.

What is a directive function?

Directive Definition. The simplest way to think about a directive is that it is simply a function that we run on a particular DOM element. The directive function can provide extra functionality on the element.


2 Answers

on related note, here my understanding of exec order across the DOM.

Here is a demo (open browser JS console)

Given this DOM using directive foo:

  <div id="1" foo>
    one
    <div id="1_1" foo>one.one</div>
  </div>

  <div id="2" foo>two</div>

...AngularJS will traverse the DOM - twice - in depth-first order:

1st pass foo.compile()

1) compile: 1

2) compile: 1_1

3) compile: 2

2nd pass: foo.controller() traversing down; foo.link() while backtracking

controller: 1

controller: 1_1

link: 1_1

link: 1

controller: 2

link: 2

like image 69
Nikita Avatar answered Sep 18 '22 22:09

Nikita


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.

Above excerpt is taken from the official docs on directives.

So, to answer your question, Post-linking/Link function is when/where you can safely operate on element.children().

like image 22
tamakisquare Avatar answered Sep 19 '22 22:09

tamakisquare