AngularJS Directives

Demystified

Tomasz Białecki, Marek Matczak

Marek Matczak

Software architect

Specializes in web applications

Impressed with JavaScript

AngularJS enthusiast

Rich web clients' designer

Tomasz Białecki

Capgemini

Software Solutions Center

Wrocław

Over 600 programmers

designers, architects,

testers, project managers

and consultants

Almost 100 projects

in different technologies

(Java, .Net, JavaScript)

from different sectors

(logistics, automotive,

financial services

and telecommunications)

We go for the Good Parts of JavaScript

Picture taken from: http://frightanic.com/category/software-development/javascript/

What are directives?

At a high level, directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS's HTML compiler to attach a specified behavior to that DOM element or even transform the DOM element and its children.

Directive declaration styles: an element name


.directive('myDirective', function(){
    return {
        restrict:'E'
    }
});
                


                

Directive declaration styles: an attribute


.directive('myDirective', function(){
    return {
        restrict:'A'
    }
});
                

Directive declaration styles: a CSS class


.directive('myDirective', function(){
    return {
        restrict:'C'
    }
});
                

Directive declaration styles: a comment


.directive('myDirective', function(){
    return {
        restrict:'M'
    }
});
                


                

Directive's scope: the parent one used


.directive('myDirective', function(){
    return {
        restrict: 'ACE'
        scope: false                    //no scope created, the parent one used
    }
});
                

Directive's scope: a child scope created


.directive('myDirective', function(){
    return {
        restrict: 'ACE'
        scope: true                     //create a child scope
    }
});
                

Directive's scope: an isolated scope created


.directive('myDirective', function(){
    return {
        restrict: 'ACE'
        scope: {                        //create an isolated scope
        }
    }
});
                

https://github.com/mmatczak/ng-directives-demystified

What is transclusion?

Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and copying them to another part of the DOM, while maintaining their connection to the original AngularJS scope from where they were taken.

Further reading

Questions?