advanced directives with angularjs

29
Advanced AngularJS Directives d3nnn1z

Upload: dionysis-pantazopoulos

Post on 08-Feb-2017

270 views

Category:

Software


2 download

TRANSCRIPT

Advanced AngularJS Directives

d3nnn1z

d3nnn1z

d3nnn1z

linkedin.com/in/d3nnn1z

Technical Team Leader @jexiaDionysis

Playing bouzouki in a local tavern in Athens

Agenda● Intro● Directive Definition Object● Scopes● Transclusion● Lifecycle● Best Practices● Q&A

Thank you ng-europe!

Intro

● Directives are the backbone of AngularJS● You already using directives ( built-in, 3rd party )● You can create your own custom elements● Reusable

Directive Restrictions

Type HTML JS

A ( Attribute )

C ( Class )

M ( coMment )

E ( Element )

{restrict: 'A'}<div card></div>

<div class=”card”></div> {restrict: 'C'}

<!-- directive: card -->

<card></card> {restrict: 'E'}

{restrict: 'M'}

DDODirective Definition Object

DDO - Directive Definition Object

What?

DDO is an object to configure your directive

Directives Scopes

Choose your scope!

Transclusion Is this a word?

TransclusionFrom angular docs:

Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.

Reaction!

TransclusionLet’s rephrase it:

The inclusion of the directive's DOM content into the directive's template

Directives Lifecycle

Step 1: Compile TOP to BOTTOM

Step 2: Pre-link TOP to BOTTOM

Step 3: Post-link BOTTOM to UP

<categories> COMPILE PRE-LINK POST-LINK

<subcategory> COMPILE PRE-LINK POST-LINK

<product> COMPILE PRE-LINK POST-LINK

Best PracticesTips

Tip #1

If you want to master directives it’s a good idea to start first with understanding the scope and then proceed with the DDO

Tip #2

When you need to modify the template or append another directive

When should I use the compile function?

Tip #3

When you need to attach events or use the scope

When should I use the link function?

Tip #4

When you want to share the $scope between nested directives

When should I use the controller method?

Tip #5

Element: When your directive has a template!Attribute: When you want to add behavior to an existing element

When should I use an element and when an attribute?

Tip #6

Always isolate the scope in a directive so that you can reuse it without worries!

Tip #7

ng-include it’s a good candidate to create your directive

Bonus Tip

Angular 1.5 introduced the component() which is much simpler than directive() and follows all the best practices around directives.

// Beforemodule.directive(name, fn);

// Aftermodule.component(name, ddo);

Thank you!

Questions?

d3nnn1z

d3nnn1z

linkedin.com/in/d3nnn1z

Dionysis