Taming AngularJS
A Directive's Lifecycle
Really quick intro to directives
Why is Angular so cool?
- MVC
- Dependency Injection
- Plain JS models
- All-in-One
- and...
Directives!
Look-and-feel
<div ng-switch-when="forked">
<div class="span1 type"><i ng-class="event.icon"></i></div>
<div class="span11">
<plunker-inline-user user="event.user"></plunker-inline-user>
created <plunker-inline-plunk plunk="event.child">{{event.child.id}}</plunker-inline-plunk>
by forking this plunk
<abbr timeago="event.date"></abbr>.
</div>
</div>
Directives
- no external templating
- declarative
- encapsulate DOM components behavior
- transparently provide two-way data binding
- are freaking mind-boggling!
By that I mean mind-boggling
terminal
priority
compile
link
pre-link
post-link
controller
transclusion
isolated scope
child scope
template element
instance element
restrict
require
Isol
Compilation, linking, and friends
Linking
Binds the directive to the scope
Code demo #1
Link and compile
Link
- DOM element instance manipulations
- binds scope to DOM
- called per element instance
Compile
- DOM element template manipulations
- no scope
- called per directive
The reasoning
Performance:
- the template is created only once
- needed if a change in a model causes a change in DOM
- saves time by simply cloning the template
You will need compilation very rarely!
Like it was not enough...
Code demo #2
Factory
Directive's factory
- constructor logic goes here
- called once per application lifecycle
- may be used for global configuration
Code demo #3
Controller
Controller
- no DOM, logic only
- created per element instance
- necessary for directive interactions
- may be used to extend scope instead or with link()
You didn't think we were done, did you?
Code demo #4
Pre- and post-linking
Pre-linking and post-linking
- pre-link executes before children link
- post-link executes after children link
- gives control over the directive build process
Lifecycle summary
- Directive is constructed
- Template element is compiled
- Scope and controller are created
- Pre-linking - linking to scope before children (if provided)
- Children are compiled and linked
- Post-linking - linking to scope after children
It couldn't end that easy
Self-study
- priority
- terminal
Q&A
Taming AngularJS: A Directive's Lifecycles
By Kiryl
Taming AngularJS: A Directive's Lifecycles
- 6,780