SlideShare a Scribd company logo
AngularJS Directives
AngularJS Directives
<tabs>
<pane title="Localization">...</pane>
<pane title="Pluralization">
<ng-pluralize count="beerCount" when="beerForms"></ng-pluralize>
</pane>
</tabs>
AngularJS Directives
AngularJS Directives
<span my-dir="exp"></span>
<span class="my-dir:exp;"></span>
<my-dir></my-dir>
<!-- directive: my-dir exp -->
Code
var app = angular.module("app", []);
app.directive('copyright', function () {
return {
restrict: 'M',
compile: function (element) {
element.text('Copyright 2013 Eyal Vardi');
}
};
});
<!-- directive: copyright -->
<!-- Copyright 2013 Eyal Vardi -->
<div draggable>Hello</div>
app.directive('draggable', function ($document) {
var startX = 0, startY = 0, x = 0, y = 0;
return function(scope, element, attr) {
element.css({ position: 'relative', cursor: 'pointer' });
element.bind('mousedown', function(event) {...});
});
<script src="/Scripts/angular.min.js"></script>
app.directive('importantBackgroundColor', function () {
return {
restrict: 'C',
priority: -99999, // we want this to be run last
// we don't use compile because we want to do this
// at the last possible minute
link: function (scope, element, attribs) {
element.css('background-color', attribs.color);
}
};
});
AngularJS Directives
myModule.directive('directiveName', function factory(injectables) {
var directiveDefinitionObject = {
priority: 0,
terminal: false,
template: '<div></div>',
templateUrl:'directive.html',
replace: false,
transclude: false,
restrict: 'A',
scope: false,
require: '^?ngModel'
controller: function($scope, $element, $attrs, $transclude, Injectables) { ... },
compile: function compile(tElement, tAttrs, transclude) {
return {
pre: function preLink(scope, iElement, iAttrs, controller) { ... },
post: function postLink(scope, iElement, iAttrs, controller) { ... }
}
},
link: function postLink(scope, iElement, iAttrs, controller) { ... }
};
return directiveDefinitionObject;
});
<div ng-controller="MyCtrl">
<ul>
<li ng-repeat="n in names">{{n}}</li>
</ul>
</div>
First the HTML is parsed into DOM
using the standard browser API.
Once all directives for a given
DOM element have been identified
they are sorted by priority and their
compile() functions are
executed.
DOM + link($scope)
Live binding between the
scope and the DOM
Register any listeners on the
elements and set up any
watches with the scope.
var $compile = ...; // injected into your code
var scope = ...;
var html = '<div ng-bind="exp"></div>';
// Step 1: parse HTML into DOM element
var template = angular.element(html);
// Step 2: compile the template
var linkFn = $compile(template);
// Step 3: link the compiled template with the
scope.
var element = linkFn(scope);
// Step 4: Append to DOM (optional)
parent.appendChild(element);
<div directive1 directive2>
<div directive3>
Hello World...
</div>
</div>
$compile start
$compile end
 Factory func
 Template
 Compile
 Controller
 preLink
 postLink
 Factory func
 No Template
 Compile
 Controller
 preLink
 postLink
 Factory func
 Template
 Compile
 Controller
 preLink
 postLink
terminal
<div directive1 directive2>
<div directive3>
Hello World...
</div>
</div>
$compile start
$compile end
 Factory func
 Template
 Compile
 Controller
 preLink
 postLink
 Factory func
 Factory func
 Template
 Compile
 Terminal = true
 Priority = 1001
 Factory func
 Template
 Compile
 Controller
 preLink
 postLink
<ul>
<li ng-repeat="x in [1,2,3,4]"
directive-name> {{x}} </li>
</ul>
AngularJS Directives
require: [ '^?ngModel', '^?Form']
function compile(tElement, tAttrs, transclude) { ... }
function link( scope, iElement, iAttrs, controller ) { ... }
function linkingFn(scope, elm, attrs, ctrl) {
// get the attribute value
console.log(attrs.ngModel);
// change the attribute
attrs.$set('ngModel', 'new value');
// observe changes to interpolated attribute
attrs.$observe('ngModel', function(value) {
console.log('ngModel has changed value to ' + value); });
}
AngularJS Directives
childScope.aString === 'parent string'
childScope.anArray[1] === 20
childScope.anObject.property1 === 'parent prop1'
childScope.aFunction() === 'parent output
childScope.aString = 'child string';childScope.aString = 'child string';
childScope.anArray[1] = '22';
childScope.anObject.property1 = 'child prop1';
This new property
hides / shadows the
parentScope property
with the same name.
childScope.anArray = [100,555];
childScope.anObject = { name: 'Mark', country: 'USA' };
AngularJS Directives
$scope.myPrimitive = 50;
$scope.myObject = { aNumber: 11 };
<script type="text/ng-template" id="/tpl1.html">
<input ng-model="myPrimitive">
</script>
<div ng-include src="'/tpl1.html'"></div>
<script type="text/ng-template" id="/tpl2.html">
<input ng-model="myObject.aNumber">
</script>
<div ng-include src="'/tpl2.html'"></div>
$scope.myPrimitive = 77;
$scope.myObject = { aNumber: 11 };
<script type="text/ng-template" id="/tpl1.html">
<input ng-model="myPrimitive">
</script>
<div ng-include src="'/tpl1.html'"></div>
<script type="text/ng-template" id="/tpl2.html">
<input ng-model="myObject.aNumber">
</script>
<div ng-include src="'/tpl2.html'"></div>
$scope.myPrimitive = 50;
$scope.myObject = { aNumber: 99 };
<script type="text/ng-template" id="/tpl1.html">
<input ng-model="myPrimitive">
</script>
<div ng-include src="'/tpl1.html'"></div>
<script type="text/ng-template" id="/tpl2.html">
<input ng-model="myObject.aNumber">
</script>
<div ng-include src="'/tpl2.html'"></div>
99
50
<script type="text/ng-template" id="/tpl1.html">
<input ng-model="$parent.myPrimitive">
</script>
<div ng-include src="'/tpl1.html'"></div>
<script type="text/ng-template" id="/tpl2.html">
<input ng-model="myObject.aNumber">
</script>
<div ng-include src="'/tpl2.html'"></div>
Typing (say, "22")
AngularJS Directives
<my-directive
interpolated ="Hello {{parentProp1}}"
twowayBinding ="parentProp2"
isolated-exp-foo ="updateFoo(newFoo)"
>
...
</my-directive>
scope: {
interpolatedProp: '@interpolated', // One-way Binding
twowayBindingProp: '=twowayBinding', // Two-way Binding
isolatedExpFooMeto: '&isolatedExpFoo' // Function Binding
}
// Option II
scope: {
interpolated: '@' ,
twowayBinding: '=' ,
isolatedExpFoo: '&'
}
Code
local scope = DOM attribute
local scope = parent scope
execute an expression in the
context of the parent scope
AngularJS Directives
AngularJS Directives
<div ng-controller="Ctrl3">
Title: <input ng-model="title"> <br>
Text: <textarea ng-model="text"></textarea>
<div class="zippy" zippy-title="Details: {{title}}">{{text}}</div>
</div>
angular.module('zippyModule', [])
.directive('zippy', function () {
return {
restrict: 'C',
replace: true,
transclude: true,
scope: { title: '@zippyTitle' },
template: '<div>' +
'<div class="title">{{title}}</div>' +
'<div class="body" ng-transclude></div>' +
'</div>',
link: function(scope, element, attrs) {...}
};
});
Code
Code
AngularJS Directives
AngularJS Directives
AngularJS.org
The Nuances of Scope Prototypal Inheritance
AngularJS Sticky Notes Pt 2 – Isolated Scope
Transclude in AngularJS

More Related Content

PDF
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
PPT
XSLT.ppt
KGSCSEPSGCT
 
PDF
javascript objects
Vijay Kalyan
 
PPT
Introduction to ADO.NET
rchakra
 
PPT
JavaScript Objects
Reem Alattas
 
PPT
7.data types in c#
Zeeshan Ahmad
 
PPTX
PHP Form Validation Technique
Morshedul Arefin
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
XSLT.ppt
KGSCSEPSGCT
 
javascript objects
Vijay Kalyan
 
Introduction to ADO.NET
rchakra
 
JavaScript Objects
Reem Alattas
 
7.data types in c#
Zeeshan Ahmad
 
PHP Form Validation Technique
Morshedul Arefin
 

What's hot (20)

PDF
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
PPTX
Friend function & friend class
Abhishek Wadhwa
 
PPTX
Form using html and java script validation
Maitree Patel
 
PPTX
Dom(document object model)
Partnered Health
 
PPTX
Database Programming
Henry Osborne
 
PPT
Builder pattern
Shakil Ahmed
 
PPTX
Lesson 6 php if...else...elseif statements
MLG College of Learning, Inc
 
PPTX
XSLT
Kamal Acharya
 
PPT
Introduction to XML
yht4ever
 
PPSX
Javascript variables and datatypes
Varun C M
 
PPTX
Exception Handling in C#
Abid Kohistani
 
PPTX
Css selectors
Parth Trivedi
 
PPTX
Flask – Python
Max Claus Nunes
 
PPTX
Windowforms controls c#
prabhu rajendran
 
PPTX
Advanced SQL
Sabiha M
 
PPTX
Cookie & Session In ASP.NET
ShingalaKrupa
 
PPTX
Generalization and specialization
Knowledge Center Computer
 
PPTX
Loops in java script
Ravi Bhadauria
 
PPTX
Delegates and events in C#
Dr.Neeraj Kumar Pandey
 
PDF
Introduction to XHTML
Hend Al-Khalifa
 
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
Friend function & friend class
Abhishek Wadhwa
 
Form using html and java script validation
Maitree Patel
 
Dom(document object model)
Partnered Health
 
Database Programming
Henry Osborne
 
Builder pattern
Shakil Ahmed
 
Lesson 6 php if...else...elseif statements
MLG College of Learning, Inc
 
Introduction to XML
yht4ever
 
Javascript variables and datatypes
Varun C M
 
Exception Handling in C#
Abid Kohistani
 
Css selectors
Parth Trivedi
 
Flask – Python
Max Claus Nunes
 
Windowforms controls c#
prabhu rajendran
 
Advanced SQL
Sabiha M
 
Cookie & Session In ASP.NET
ShingalaKrupa
 
Generalization and specialization
Knowledge Center Computer
 
Loops in java script
Ravi Bhadauria
 
Delegates and events in C#
Dr.Neeraj Kumar Pandey
 
Introduction to XHTML
Hend Al-Khalifa
 
Ad

Viewers also liked (20)

PPTX
AngularJS Architecture
Eyal Vardi
 
PPTX
Forms in AngularJS
Eyal Vardi
 
PPTX
AngularJS Services
Eyal Vardi
 
PPTX
AngularJS Routing
Eyal Vardi
 
PPTX
AngularJS Animations
Eyal Vardi
 
PPTX
AngulrJS Overview
Eyal Vardi
 
PDF
Intro to Angular.JS Directives
Christian Lilley
 
PPTX
BDOTNET AngularJs Directives - Uday
Udaya Kumar
 
PPTX
AngularJS Filters
Eyal Vardi
 
PPTX
AngularJS - $http & $resource Services
Eyal Vardi
 
PPTX
AngularJS Testing
Eyal Vardi
 
PPTX
Introduction to Angularjs
Manish Shekhawat
 
PPTX
AngularJS Compile Process
Eyal Vardi
 
PDF
Building Custom AngularJS Directives - A Step-by-Step Guide - Dan Wahlin | Fa...
FalafelSoftware
 
PPTX
Building AngularJS Custom Directives
Dan Wahlin
 
PDF
Diamante poem
Liz Slavens
 
PPTX
AngularJS Internal
Eyal Vardi
 
PDF
AngularJS - TechTalk 3/2/2014
Spyros Ioakeimidis
 
PPTX
Async & Parallel in JavaScript
Eyal Vardi
 
PPTX
OOP in JavaScript
Eyal Vardi
 
AngularJS Architecture
Eyal Vardi
 
Forms in AngularJS
Eyal Vardi
 
AngularJS Services
Eyal Vardi
 
AngularJS Routing
Eyal Vardi
 
AngularJS Animations
Eyal Vardi
 
AngulrJS Overview
Eyal Vardi
 
Intro to Angular.JS Directives
Christian Lilley
 
BDOTNET AngularJs Directives - Uday
Udaya Kumar
 
AngularJS Filters
Eyal Vardi
 
AngularJS - $http & $resource Services
Eyal Vardi
 
AngularJS Testing
Eyal Vardi
 
Introduction to Angularjs
Manish Shekhawat
 
AngularJS Compile Process
Eyal Vardi
 
Building Custom AngularJS Directives - A Step-by-Step Guide - Dan Wahlin | Fa...
FalafelSoftware
 
Building AngularJS Custom Directives
Dan Wahlin
 
Diamante poem
Liz Slavens
 
AngularJS Internal
Eyal Vardi
 
AngularJS - TechTalk 3/2/2014
Spyros Ioakeimidis
 
Async & Parallel in JavaScript
Eyal Vardi
 
OOP in JavaScript
Eyal Vardi
 
Ad

Similar to AngularJS Directives (20)

PDF
Hey, I just met AngularJS, and this is crazy, so here’s my JavaScript, let’s ...
Alessandro Nadalin
 
PDF
"Inside The AngularJS Directive Compiler" by Tero Parviainen
Fwdays
 
PDF
Angular custom directives
Alexe Bogdan
 
PDF
Angular js is the future. maybe. @ ConFoo 2014 in Montreal (CA)
Alessandro Nadalin
 
PPTX
AngularJS
LearningTech
 
PPTX
Angular Deep Directive
Henry Tao
 
PDF
Angular.js Primer in Aalto University
SC5.io
 
PDF
AngularJS Basic Training
Cornel Stefanache
 
PPTX
Angular Workshop_Sarajevo2
Christoffer Noring
 
DOCX
Angular js
prasaddammalapati
 
PDF
Get AngularJS Started!
Dzmitry Ivashutsin
 
PDF
AngularJS CheatSheet
Abdul Basit
 
PPTX
Angular
LearningTech
 
PPTX
Angular
LearningTech
 
PPTX
Optimizing a large angular application (ng conf)
A K M Zahiduzzaman
 
PPTX
Angular Presentation
Adam Moore
 
PPTX
Angular workshop - Full Development Guide
Nitin Giri
 
PDF
Angular 2.0 - What to expect
Allan Marques Baptista
 
PDF
Introduction to AngularJS
Jussi Pohjolainen
 
PDF
Mini-Training: AngularJS
Betclic Everest Group Tech Team
 
Hey, I just met AngularJS, and this is crazy, so here’s my JavaScript, let’s ...
Alessandro Nadalin
 
"Inside The AngularJS Directive Compiler" by Tero Parviainen
Fwdays
 
Angular custom directives
Alexe Bogdan
 
Angular js is the future. maybe. @ ConFoo 2014 in Montreal (CA)
Alessandro Nadalin
 
AngularJS
LearningTech
 
Angular Deep Directive
Henry Tao
 
Angular.js Primer in Aalto University
SC5.io
 
AngularJS Basic Training
Cornel Stefanache
 
Angular Workshop_Sarajevo2
Christoffer Noring
 
Angular js
prasaddammalapati
 
Get AngularJS Started!
Dzmitry Ivashutsin
 
AngularJS CheatSheet
Abdul Basit
 
Angular
LearningTech
 
Angular
LearningTech
 
Optimizing a large angular application (ng conf)
A K M Zahiduzzaman
 
Angular Presentation
Adam Moore
 
Angular workshop - Full Development Guide
Nitin Giri
 
Angular 2.0 - What to expect
Allan Marques Baptista
 
Introduction to AngularJS
Jussi Pohjolainen
 
Mini-Training: AngularJS
Betclic Everest Group Tech Team
 

More from Eyal Vardi (20)

PPTX
Why magic
Eyal Vardi
 
PPTX
Smart Contract
Eyal Vardi
 
PDF
Rachel's grandmother's recipes
Eyal Vardi
 
PPTX
Performance Optimization In Angular 2
Eyal Vardi
 
PPTX
Angular 2 Architecture (Bucharest 26/10/2016)
Eyal Vardi
 
PPTX
Angular 2 NgModule
Eyal Vardi
 
PPTX
Upgrading from Angular 1.x to Angular 2.x
Eyal Vardi
 
PPTX
Angular 2 - Ahead of-time Compilation
Eyal Vardi
 
PPTX
Routing And Navigation
Eyal Vardi
 
PPTX
Angular 2 Architecture
Eyal Vardi
 
PPTX
Angular 1.x vs. Angular 2.x
Eyal Vardi
 
PPTX
Angular 2.0 Views
Eyal Vardi
 
PPTX
Component lifecycle hooks in Angular 2.0
Eyal Vardi
 
PPTX
Template syntax in Angular 2.0
Eyal Vardi
 
PPTX
Http Communication in Angular 2.0
Eyal Vardi
 
PPTX
Angular 2.0 Dependency injection
Eyal Vardi
 
PPTX
Angular 2.0 Routing and Navigation
Eyal Vardi
 
PPTX
Async & Parallel in JavaScript
Eyal Vardi
 
PPTX
Angular 2.0 Pipes
Eyal Vardi
 
PPTX
Angular 2.0 forms
Eyal Vardi
 
Why magic
Eyal Vardi
 
Smart Contract
Eyal Vardi
 
Rachel's grandmother's recipes
Eyal Vardi
 
Performance Optimization In Angular 2
Eyal Vardi
 
Angular 2 Architecture (Bucharest 26/10/2016)
Eyal Vardi
 
Angular 2 NgModule
Eyal Vardi
 
Upgrading from Angular 1.x to Angular 2.x
Eyal Vardi
 
Angular 2 - Ahead of-time Compilation
Eyal Vardi
 
Routing And Navigation
Eyal Vardi
 
Angular 2 Architecture
Eyal Vardi
 
Angular 1.x vs. Angular 2.x
Eyal Vardi
 
Angular 2.0 Views
Eyal Vardi
 
Component lifecycle hooks in Angular 2.0
Eyal Vardi
 
Template syntax in Angular 2.0
Eyal Vardi
 
Http Communication in Angular 2.0
Eyal Vardi
 
Angular 2.0 Dependency injection
Eyal Vardi
 
Angular 2.0 Routing and Navigation
Eyal Vardi
 
Async & Parallel in JavaScript
Eyal Vardi
 
Angular 2.0 Pipes
Eyal Vardi
 
Angular 2.0 forms
Eyal Vardi
 

Recently uploaded (20)

PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
PPTX
Coupa-Overview _Assumptions presentation
annapureddyn
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PPTX
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
Doc9.....................................
SofiaCollazos
 
PPT
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PPT
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PPTX
Stamford - Community User Group Leaders_ Agentblazer Status, AI Sustainabilit...
Amol Dixit
 
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
Coupa-Overview _Assumptions presentation
annapureddyn
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Doc9.....................................
SofiaCollazos
 
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
Stamford - Community User Group Leaders_ Agentblazer Status, AI Sustainabilit...
Amol Dixit
 
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 

AngularJS Directives

  • 3. <tabs> <pane title="Localization">...</pane> <pane title="Pluralization"> <ng-pluralize count="beerCount" when="beerForms"></ng-pluralize> </pane> </tabs>
  • 7. var app = angular.module("app", []); app.directive('copyright', function () { return { restrict: 'M', compile: function (element) { element.text('Copyright 2013 Eyal Vardi'); } }; }); <!-- directive: copyright --> <!-- Copyright 2013 Eyal Vardi -->
  • 8. <div draggable>Hello</div> app.directive('draggable', function ($document) { var startX = 0, startY = 0, x = 0, y = 0; return function(scope, element, attr) { element.css({ position: 'relative', cursor: 'pointer' }); element.bind('mousedown', function(event) {...}); });
  • 9. <script src="/Scripts/angular.min.js"></script> app.directive('importantBackgroundColor', function () { return { restrict: 'C', priority: -99999, // we want this to be run last // we don't use compile because we want to do this // at the last possible minute link: function (scope, element, attribs) { element.css('background-color', attribs.color); } }; });
  • 11. myModule.directive('directiveName', function factory(injectables) { var directiveDefinitionObject = { priority: 0, terminal: false, template: '<div></div>', templateUrl:'directive.html', replace: false, transclude: false, restrict: 'A', scope: false, require: '^?ngModel' controller: function($scope, $element, $attrs, $transclude, Injectables) { ... }, compile: function compile(tElement, tAttrs, transclude) { return { pre: function preLink(scope, iElement, iAttrs, controller) { ... }, post: function postLink(scope, iElement, iAttrs, controller) { ... } } }, link: function postLink(scope, iElement, iAttrs, controller) { ... } }; return directiveDefinitionObject; });
  • 12. <div ng-controller="MyCtrl"> <ul> <li ng-repeat="n in names">{{n}}</li> </ul> </div> First the HTML is parsed into DOM using the standard browser API. Once all directives for a given DOM element have been identified they are sorted by priority and their compile() functions are executed. DOM + link($scope) Live binding between the scope and the DOM Register any listeners on the elements and set up any watches with the scope. var $compile = ...; // injected into your code var scope = ...; var html = '<div ng-bind="exp"></div>'; // Step 1: parse HTML into DOM element var template = angular.element(html); // Step 2: compile the template var linkFn = $compile(template); // Step 3: link the compiled template with the scope. var element = linkFn(scope); // Step 4: Append to DOM (optional) parent.appendChild(element);
  • 13. <div directive1 directive2> <div directive3> Hello World... </div> </div> $compile start $compile end  Factory func  Template  Compile  Controller  preLink  postLink  Factory func  No Template  Compile  Controller  preLink  postLink  Factory func  Template  Compile  Controller  preLink  postLink
  • 14. terminal <div directive1 directive2> <div directive3> Hello World... </div> </div> $compile start $compile end  Factory func  Template  Compile  Controller  preLink  postLink  Factory func  Factory func  Template  Compile  Terminal = true  Priority = 1001
  • 15.  Factory func  Template  Compile  Controller  preLink  postLink <ul> <li ng-repeat="x in [1,2,3,4]" directive-name> {{x}} </li> </ul>
  • 18. function compile(tElement, tAttrs, transclude) { ... }
  • 19. function link( scope, iElement, iAttrs, controller ) { ... }
  • 20. function linkingFn(scope, elm, attrs, ctrl) { // get the attribute value console.log(attrs.ngModel); // change the attribute attrs.$set('ngModel', 'new value'); // observe changes to interpolated attribute attrs.$observe('ngModel', function(value) { console.log('ngModel has changed value to ' + value); }); }
  • 22. childScope.aString === 'parent string' childScope.anArray[1] === 20 childScope.anObject.property1 === 'parent prop1' childScope.aFunction() === 'parent output
  • 23. childScope.aString = 'child string';childScope.aString = 'child string'; childScope.anArray[1] = '22'; childScope.anObject.property1 = 'child prop1'; This new property hides / shadows the parentScope property with the same name.
  • 24. childScope.anArray = [100,555]; childScope.anObject = { name: 'Mark', country: 'USA' };
  • 26. $scope.myPrimitive = 50; $scope.myObject = { aNumber: 11 }; <script type="text/ng-template" id="/tpl1.html"> <input ng-model="myPrimitive"> </script> <div ng-include src="'/tpl1.html'"></div> <script type="text/ng-template" id="/tpl2.html"> <input ng-model="myObject.aNumber"> </script> <div ng-include src="'/tpl2.html'"></div>
  • 27. $scope.myPrimitive = 77; $scope.myObject = { aNumber: 11 }; <script type="text/ng-template" id="/tpl1.html"> <input ng-model="myPrimitive"> </script> <div ng-include src="'/tpl1.html'"></div> <script type="text/ng-template" id="/tpl2.html"> <input ng-model="myObject.aNumber"> </script> <div ng-include src="'/tpl2.html'"></div>
  • 28. $scope.myPrimitive = 50; $scope.myObject = { aNumber: 99 }; <script type="text/ng-template" id="/tpl1.html"> <input ng-model="myPrimitive"> </script> <div ng-include src="'/tpl1.html'"></div> <script type="text/ng-template" id="/tpl2.html"> <input ng-model="myObject.aNumber"> </script> <div ng-include src="'/tpl2.html'"></div> 99 50
  • 29. <script type="text/ng-template" id="/tpl1.html"> <input ng-model="$parent.myPrimitive"> </script> <div ng-include src="'/tpl1.html'"></div> <script type="text/ng-template" id="/tpl2.html"> <input ng-model="myObject.aNumber"> </script> <div ng-include src="'/tpl2.html'"></div> Typing (say, "22")
  • 31. <my-directive interpolated ="Hello {{parentProp1}}" twowayBinding ="parentProp2" isolated-exp-foo ="updateFoo(newFoo)" > ... </my-directive> scope: { interpolatedProp: '@interpolated', // One-way Binding twowayBindingProp: '=twowayBinding', // Two-way Binding isolatedExpFooMeto: '&isolatedExpFoo' // Function Binding } // Option II scope: { interpolated: '@' , twowayBinding: '=' , isolatedExpFoo: '&' } Code local scope = DOM attribute local scope = parent scope execute an expression in the context of the parent scope
  • 34. <div ng-controller="Ctrl3"> Title: <input ng-model="title"> <br> Text: <textarea ng-model="text"></textarea> <div class="zippy" zippy-title="Details: {{title}}">{{text}}</div> </div> angular.module('zippyModule', []) .directive('zippy', function () { return { restrict: 'C', replace: true, transclude: true, scope: { title: '@zippyTitle' }, template: '<div>' + '<div class="title">{{title}}</div>' + '<div class="body" ng-transclude></div>' + '</div>', link: function(scope, element, attrs) {...} }; }); Code
  • 35. Code
  • 38. AngularJS.org The Nuances of Scope Prototypal Inheritance AngularJS Sticky Notes Pt 2 – Isolated Scope Transclude in AngularJS