SlideShare a Scribd company logo
AngularJS Architecture
HTML
Browser
Static
DOM
Dynamic
DOM
(View)
AngularJS
DOM
Content
Loaded
Event
ng-app=“module”
$injector
$compile $rootScope
$compile (dom,
$rootScope)
(function (window, document, undefined) {
'use strict';
// Functions declerations
jqLite(document).ready(function () {
angularInit(document, bootstrap);
});
})(window, document);
angularInit
bootstrap
doBootstrap
<html >
<body>
Hello {{'World'}}!
<script src="angular.js"></script>
<script>
angular.element(document).ready(function () {
angular.module('myApp', []);
angular.bootstrap(document, ['myApp']);
});
</script>
</body>
</html>
AngularJS Architecture
AngularJS Architecture
AngularJS Architecture
// Create a module
var myModule = angular.module('myModule', [])
// Configure the injector
myModule.factory('serviceA', function () {
return {
// instead of {}, put your object creation here
};
});
// create an injector and configure it from 'myModule'
var $injector = angular.injector(['myModule']);
// retrieve an object from the injector by name
var serviceA = $injector.get('serviceA');
// always true because of instance cache
$injector.get('serviceA') === $injector.get('serviceA');
// inferred (only works if code not minified/obfuscated)
$injector.invoke(function (serviceA) { });
// annotated
function explicit(serviceA) { };
explicit.$inject = ['serviceA'];
$injector.invoke(explicit);
// inline
$injector.invoke(['serviceA', function (serviceA) { }]);
// You write functions such as this one.
function doSomething(serviceA, serviceB) {
// do something here.
}
// Angular provides the injector for your application
var $injector = ...;
///////////////////////////////////////////////
// the old-school way of getting dependencies.
var serviceA = $injector.get('serviceA');
var serviceB = $injector.get('serviceB');
// now call the function
doSomething(serviceA, serviceB);
///////////////////////////////////////////////
// the cool way of getting dependencies.
$injector.invoke(doSomething)
$injector
Instance Cache
Provider Injector
instantiate
instantiate
Provider Cache
AngularJS Architecture
Config ( function( xxxProvider ){} )
Registration
- controller(name, constructor)
- directive(name, directiveFn)
- filter(name, filterFactory)
Registration ($provide)
- service(name, constructor)
- factory(name, providerFn)
- provider(name, providerType)
- decorator(name, fn )
- constant(name, object)
- value(name, object)
run(initializationFn)
Execute when the injector is done loading all modules.
ngXXX
angular.module('myApp', ['ngXXX', 'ngYYY']);
Constant
Provider
ngYYY
Constant
Providers
myApp
Constant
Providers
Config Config Config
Run Run Run
$injector
Instance
Cache
Provider
Cache
AngularJS Architecture
<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
the directive 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.
linkFn(scope);
var myModule = angular.module(...);
myModule.directive('directiveName', function factory(injectables) {
var directiveDefinitionObject = {
priority: 0,
template: '<div></div>', // or function
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 directive1 directive2>
<div directive3>
Hello World...
</div>
</div>
$compile start
$compile end
 Factory func
 Template
 Compile
 Controller
 preLink
 postLink
 Factory func
 Template
 Compile
 Controller
 preLink
 postLink
 Factory func
 Template
 Compile
 Controller
 preLink
 postLink
function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
previousCompileContext) {
...
var compositeLinkFn =
compileNodes( compileNodes, transcludeFn, $compileNodes,
maxPriority, ignoreDirective, previousCompileContext);
...
return function publicLinkFn(scope, cloneConnectFn, transcludeControllers) {
...
};
}
 Create all the DDO’s
 Execute all DDO’s template property or function
 Execute all DDO’s compile functions
 Execute all DDO’s controllers
 Execute all DDO’s preLink functions
 Execute all DDO’s postLink functions
function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority,
ignoreDirective, previousCompileContext) {
...
for (var i = 0; i < nodeList.length; i++) {
attrs = new Attributes();
directives = collectDirectives(nodeList[i], [], attrs,
i === 0 ? maxPriority : undefined, ignoreDirective);
nodeLinkFn = (directives.length)
? applyDirectivesToNode(directives, nodeList[i], attrs, ...)
: null;
...
childLinkFn = (nodeLinkFn ...) ? null : compileNodes( childNodes , ...);
...
}
...
}
 Scan the DOM (DFS) and find all directives
 Sort the directive by priority
 Execute the directive factory and store the DDO
 Call to the DDO.template
 Call to the DDO.compile
 Execute the compileNodes on the child nodes of
nodeList[i]
function bootstrap(element, modules) {
...
function(scope, element, compile, injector, animate) {
scope.$apply(function() {
element.data('$injector', injector);
compile(element)(scope);
});
...
}
<div directive1 directive2>
<div directive3>
Hello World...
</div>
</div>
$compile start
$compile end
 Factory func
 Template
 Compile
 Controller
 preLink
 postLink
 Factory func
 Template
 Compile
 Controller
 preLink
 postLink
 Factory func
 Template
 Compile
 Controller
 preLink
 postLink
AngularJS Architecture
 Factory func
 Template
 Compile
 Controller
 preLink
 postLink
<ul>
<li ng-repeat="x in [1,2,3,4]"
directive-name> {{x}} </li>
</ul>
var parseFn = $parse(' expression ');
var resultValue = parseFn($scope);
// Set value to expression
var setter = parseFn.assign;
setter(context,value);
Do in
compile
var temp = $interpolate( "{{a}}+{{b}}=<b>{{ result }}</b>" );
var result = temp( {a: '2', b: '3', result: '5'} );
Do in
compile $parse $parse $parse
$compile
$interpolate
$parse
<!-- Expressions -->
Please type your name : {{name}}
<!-- Directives & Data Binding -->
Name: <input ng-model="name" value="..." />
Template
name :
Scope
value
elm.bind('keydown', … )
$scope.$watch('name', … )
Directive
Native
Event
Queue
(wait)
DOM
Render
JavaScript
AngularJS
Event
Loop
$eval
Async
queue
$watch
list
// Pseudo-Code of $apply()
function $apply(expr) {
try {
return $eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
$root.$digest();
}
}
...
var dereg = $scope.$watch('Model.Property', callbackOnChange());
…
// de-register $watch
dereg();
AngularJS Architecture
AngularJS Architecture
Counter = 0Counter = 1
scope.name = 'misko';
scope.counter = 0;
scope.$watch('name', function(newValue, oldValue)
{
scope.counter = scope.counter + 1;
});
scope.$digest();
scope.name = 'adam';
scope.$digest();
AngularJS Architecture
Root Scope
Scope
Scope Scope
AngularJS Architecture
Scope Type Properties:
 $id
Events:
 $destroy
Lifecycle Methods
 $destroy()
 $new(isolate)
Communication Methods:
 $broadcast(name, args)
 $emit(name, args)
 $on(name, listener)
Runtime Methods:
 $watch(…)
 $apply(exp)
 $digest()
 $eval(exp)
 $evalAsync(exp)
AngularJS Architecture

More Related Content

PDF
Spring Framework - Core
PPTX
Angular Data Binding
PDF
Spring Boot
PPTX
Sharing Data Between Angular Components
PPTX
Spring Web MVC
PPTX
Introduction à spring boot
PPSX
Spring - Part 1 - IoC, Di and Beans
PDF
Angular Directives
Spring Framework - Core
Angular Data Binding
Spring Boot
Sharing Data Between Angular Components
Spring Web MVC
Introduction à spring boot
Spring - Part 1 - IoC, Di and Beans
Angular Directives

What's hot (20)

PDF
Angular - Chapter 7 - HTTP Services
PDF
An introduction to React.js
PPTX
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
PDF
TypeScript Introduction
PPT
Java EE Introduction
PPTX
Springboot Microservices
PDF
JUnit 5 - The Next Generation
PPTX
Angular 2.0 forms
PPT
jQuery Ajax
PPT
Spring ppt
PDF
Deep Dive Java 17 Devoxx UK
PDF
Introduction to JWT and How to integrate with Spring Security
PPTX
빠르게훓어보는 Node.js와 Vert.x
PDF
How to Avoid Common Mistakes When Using Reactor Netty
PPTX
Spring Boot Tutorial
PDF
TypeScript
PPTX
Java 8 Lambda and Streams
PPTX
Jsf presentation
PPTX
Spring mvc
PDF
Java design patterns
Angular - Chapter 7 - HTTP Services
An introduction to React.js
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
TypeScript Introduction
Java EE Introduction
Springboot Microservices
JUnit 5 - The Next Generation
Angular 2.0 forms
jQuery Ajax
Spring ppt
Deep Dive Java 17 Devoxx UK
Introduction to JWT and How to integrate with Spring Security
빠르게훓어보는 Node.js와 Vert.x
How to Avoid Common Mistakes When Using Reactor Netty
Spring Boot Tutorial
TypeScript
Java 8 Lambda and Streams
Jsf presentation
Spring mvc
Java design patterns
Ad

Similar to AngularJS Architecture (20)

PPTX
AngularJS Compile Process
PPTX
AngularJS Directives
PDF
Introduction to angular js
PDF
Patterns Are Good For Managers
PDF
The Naked Bundle - Tryout
PDF
Symfony2 from the Trenches
PDF
Symfony2 - from the trenches
PDF
"Angular.js Concepts in Depth" by Aleksandar Simović
PDF
HTML5 for the Silverlight Guy
PDF
IOC + Javascript
PDF
Google App Engine in 40 minutes (the absolute essentials)
PDF
Building Reusable Custom Elements With Angular
PDF
Writing Maintainable JavaScript
PPT
Building Single Page Application (SPA) with Symfony2 and AngularJS
PDF
Angular JS2 Training Session #2
PDF
Clean Javascript
PDF
Build powerfull and smart web applications with Symfony2
PPTX
Practical AngularJS
PDF
How AngularJS Embraced Traditional Design Patterns
AngularJS Compile Process
AngularJS Directives
Introduction to angular js
Patterns Are Good For Managers
The Naked Bundle - Tryout
Symfony2 from the Trenches
Symfony2 - from the trenches
"Angular.js Concepts in Depth" by Aleksandar Simović
HTML5 for the Silverlight Guy
IOC + Javascript
Google App Engine in 40 minutes (the absolute essentials)
Building Reusable Custom Elements With Angular
Writing Maintainable JavaScript
Building Single Page Application (SPA) with Symfony2 and AngularJS
Angular JS2 Training Session #2
Clean Javascript
Build powerfull and smart web applications with Symfony2
Practical AngularJS
How AngularJS Embraced Traditional Design Patterns
Ad

More from Eyal Vardi (20)

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

Recently uploaded (20)

PPTX
Cloud computing and distributed systems.
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Sensors and Actuators in IoT Systems using pdf
PDF
KodekX | Application Modernization Development
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
PDF
Modernizing your data center with Dell and AMD
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Advanced Soft Computing BINUS July 2025.pdf
PDF
Advanced IT Governance
Cloud computing and distributed systems.
20250228 LYD VKU AI Blended-Learning.pptx
Sensors and Actuators in IoT Systems using pdf
KodekX | Application Modernization Development
Reach Out and Touch Someone: Haptics and Empathic Computing
NewMind AI Monthly Chronicles - July 2025
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
MYSQL Presentation for SQL database connectivity
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
Modernizing your data center with Dell and AMD
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Advanced Soft Computing BINUS July 2025.pdf
Advanced IT Governance

AngularJS Architecture

  • 3. (function (window, document, undefined) { 'use strict'; // Functions declerations jqLite(document).ready(function () { angularInit(document, bootstrap); }); })(window, document); angularInit bootstrap doBootstrap
  • 4. <html > <body> Hello {{'World'}}! <script src="angular.js"></script> <script> angular.element(document).ready(function () { angular.module('myApp', []); angular.bootstrap(document, ['myApp']); }); </script> </body> </html>
  • 8. // Create a module var myModule = angular.module('myModule', []) // Configure the injector myModule.factory('serviceA', function () { return { // instead of {}, put your object creation here }; }); // create an injector and configure it from 'myModule' var $injector = angular.injector(['myModule']); // retrieve an object from the injector by name var serviceA = $injector.get('serviceA'); // always true because of instance cache $injector.get('serviceA') === $injector.get('serviceA');
  • 9. // inferred (only works if code not minified/obfuscated) $injector.invoke(function (serviceA) { }); // annotated function explicit(serviceA) { }; explicit.$inject = ['serviceA']; $injector.invoke(explicit); // inline $injector.invoke(['serviceA', function (serviceA) { }]);
  • 10. // You write functions such as this one. function doSomething(serviceA, serviceB) { // do something here. } // Angular provides the injector for your application var $injector = ...; /////////////////////////////////////////////// // the old-school way of getting dependencies. var serviceA = $injector.get('serviceA'); var serviceB = $injector.get('serviceB'); // now call the function doSomething(serviceA, serviceB); /////////////////////////////////////////////// // the cool way of getting dependencies. $injector.invoke(doSomething)
  • 13. Config ( function( xxxProvider ){} ) Registration - controller(name, constructor) - directive(name, directiveFn) - filter(name, filterFactory) Registration ($provide) - service(name, constructor) - factory(name, providerFn) - provider(name, providerType) - decorator(name, fn ) - constant(name, object) - value(name, object) run(initializationFn) Execute when the injector is done loading all modules.
  • 16. <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 the directive 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. linkFn(scope);
  • 17. var myModule = angular.module(...); myModule.directive('directiveName', function factory(injectables) { var directiveDefinitionObject = { priority: 0, template: '<div></div>', // or function 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; });
  • 18. <div directive1 directive2> <div directive3> Hello World... </div> </div> $compile start $compile end  Factory func  Template  Compile  Controller  preLink  postLink  Factory func  Template  Compile  Controller  preLink  postLink  Factory func  Template  Compile  Controller  preLink  postLink
  • 19. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective, previousCompileContext) { ... var compositeLinkFn = compileNodes( compileNodes, transcludeFn, $compileNodes, maxPriority, ignoreDirective, previousCompileContext); ... return function publicLinkFn(scope, cloneConnectFn, transcludeControllers) { ... }; }  Create all the DDO’s  Execute all DDO’s template property or function  Execute all DDO’s compile functions  Execute all DDO’s controllers  Execute all DDO’s preLink functions  Execute all DDO’s postLink functions
  • 20. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective, previousCompileContext) { ... for (var i = 0; i < nodeList.length; i++) { attrs = new Attributes(); directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined, ignoreDirective); nodeLinkFn = (directives.length) ? applyDirectivesToNode(directives, nodeList[i], attrs, ...) : null; ... childLinkFn = (nodeLinkFn ...) ? null : compileNodes( childNodes , ...); ... } ... }  Scan the DOM (DFS) and find all directives  Sort the directive by priority  Execute the directive factory and store the DDO  Call to the DDO.template  Call to the DDO.compile  Execute the compileNodes on the child nodes of nodeList[i]
  • 21. function bootstrap(element, modules) { ... function(scope, element, compile, injector, animate) { scope.$apply(function() { element.data('$injector', injector); compile(element)(scope); }); ... } <div directive1 directive2> <div directive3> Hello World... </div> </div> $compile start $compile end  Factory func  Template  Compile  Controller  preLink  postLink  Factory func  Template  Compile  Controller  preLink  postLink  Factory func  Template  Compile  Controller  preLink  postLink
  • 23.  Factory func  Template  Compile  Controller  preLink  postLink <ul> <li ng-repeat="x in [1,2,3,4]" directive-name> {{x}} </li> </ul>
  • 24. var parseFn = $parse(' expression '); var resultValue = parseFn($scope); // Set value to expression var setter = parseFn.assign; setter(context,value); Do in compile
  • 25. var temp = $interpolate( "{{a}}+{{b}}=<b>{{ result }}</b>" ); var result = temp( {a: '2', b: '3', result: '5'} ); Do in compile $parse $parse $parse
  • 27. <!-- Expressions --> Please type your name : {{name}} <!-- Directives & Data Binding --> Name: <input ng-model="name" value="..." /> Template name : Scope value elm.bind('keydown', … ) $scope.$watch('name', … ) Directive
  • 29. // Pseudo-Code of $apply() function $apply(expr) { try { return $eval(expr); } catch (e) { $exceptionHandler(e); } finally { $root.$digest(); } }
  • 30. ... var dereg = $scope.$watch('Model.Property', callbackOnChange()); … // de-register $watch dereg();
  • 33. Counter = 0Counter = 1 scope.name = 'misko'; scope.counter = 0; scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; }); scope.$digest(); scope.name = 'adam'; scope.$digest();
  • 37. Scope Type Properties:  $id Events:  $destroy Lifecycle Methods  $destroy()  $new(isolate) Communication Methods:  $broadcast(name, args)  $emit(name, args)  $on(name, listener) Runtime Methods:  $watch(…)  $apply(exp)  $digest()  $eval(exp)  $evalAsync(exp)