SlideShare a Scribd company logo
AngularJS: what is underneath the hood
- the less routine code the happier developers
- good application structure
two-way data binding
- directives
- testability
- active community / cool documentation, etc...
var btn = document.getElementById("myBtn");
btn.addEventListener("click", onClick);
function onClick(evt) {
// some code
}
<button ng-click=”onClick($event)”></button>
element.on(‘click’, function(event){
var callback = function(){
fn(scope, {$event: event});
}
scope.$apply(callback);
})
<span>{{myModel}}</span>
function myController($scope, $timeout) {
$scope.myModel = ‘value1’;
setTimeout(function(){
$scope.myModel = ‘value2’;
}, 500);
$timeout(function(){
$scope.myModel = ‘value2’;
}, 500);
}
scope.$watch(‘someModel2’,
callback);
{{someModel}}, ng-bind
ng-repeat, ng-model..
$timeout(fn) с нулевой
задержкой
scope.$evalAsync(fn)
$watch list $evalAsync list
step 1:
function Scope() {
}
step 2:
function Scope() {
this.$$watchers = [];
}
step 3:
Scope.prototype.$watch = function(watchFn, listenerFn) {
var watcher = {
watchFn: watchFn,
listenerFn: listenerFn
};
this.$$watchers.push(watcher);
};
$watchList implementation
step 4:
Scope.prototype.$digest = function() {
_.forEach(this.$$watchers, function(watch) {
watch.listenerFn();
});
};
step 5:
Scope.prototype.$digest = function() {
var self = this;
_.forEach(this.$$watchers, function(watch) {
var newValue = watch.watchFn(self);
var oldValue = watch.last;
if (newValue !== oldValue) {
watch.listenerFn(newValue, oldValue, self);
}
watch.last = newValue;
});
};
...
$scope.$watch(‘myModel’, function(){
alert(‘My model was changed’);
});
$scope.$watch(‘yourModel’, function(){
scope.myModel = ‘someValue’;
});
...
<input type=”text” ng-model=”yourModel” />
Scope.prototype.$digest = function() {
var self = this;
var dirty;
do {
dirty = false;
_.forEach(this.$$watchers, function(watch) {
var newValue = watch.watchFn(self);
var oldValue = watch.last;
if (newValue !== oldValue) {
watch.listenerFn(newValue, oldValue, self);
dirty = true;
}
watch.last = newValue;
});
} while (dirty);
};
DIRTY CHECK
step 1:
function Scope() {
this.$$watchers = [];
this.$$asyncQueue = [];
}
step 2:
Scope.prototype.$evalAsync = function(expr) {
var obj = {scope: this, expression: expr};
this.$$asyncQueue.push(obj);
};
step 3:
Scope.prototype.$digest = function() {
while (this.$$asyncQueue.length) {
var asyncTask = this.$$asyncQueue.shift();
this.$eval(asyncTask.expression);
}
...
};
$watchList implementation$evalAsync implementation
function myCtrl($scope, $rootScope) {
$scope.myModel = ‘value1’;
$scope.$evalAsync(function()
{
console.log($scope.myModel);
});
$scope.myModel = ‘value2’;
}
$scope.$apply vs $scope.$digest
<body ng-app=”myApp”>{{rootMessage}}
<div ng-controller=”myCtrl”>{{childMessage}}</div>
</body>
function myCtrl($scope, $rootScope) {
$rootScope.rootMessage = ‘root message’;
$scope.childMessage = ‘child message’;
setTimeout(function(){
$rootScope.rootMessage = ‘new root message’;
$scope.childMessage = ‘new child message’;
$scope.apply(); // both model are re-rendered
$scope.digest(); // only childMessage
}, 5000); }
setTimeout(function(){
$scope.apply(function(){//some code});
}, 5000); }
$apply: function(expr) {
try {
return this.$eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
try {
$rootScope.$digest();
} catch (e) {
$exceptionHandler(e);
throw e;
}
}}
SOME OPTIMIZATION TIPS
- minimize watchers:
- limit DOM filters
- use onetime binding when possible ng-bind=”::myModel” ng-
repeat=”item in ::items” or bindonce if Angular < 1.3
- lightweight watch-functions and callbacks in watchers
- ng-repeat=”item in items track by item.id”
- $watchCollection instead of $watch with 3rd parameter equaled true
- debounce ng-model <input ng-model=”myModel” ng-model-
options=”{debounce: 500}” />
- use native JS or lodash (for example, simple ‘for’ loop instead of
angular.forEach )
- use directive ng-bind instead of {{}};
$parse
$scope.$watch(function() {
return $scope.myModel;
}, callback);
$scope.$watch(‘myModel’, callback);
$watch: function(watchExp, listener, objectEquality){
var get = $parse(watchExp);...
}
$eval: function(expr, locals) {
return $parse(expr)(this, locals);
},
DEPENDENCY INJECTION IN ANGULAR
Dependency Injection is a software design pattern in which an object is given its
dependencies, rather than the object creating them itself.
angular.module(‘myApp’, []);
angular.module(‘myApp’)
.controller(‘myController’, myController);
function myController($scope, $timeout, myService) {
// some code goes here
}
function myController($timeout, $scope, myService) {
// some code goes here
}
ISSUES WITH IMPLICIT DEPENDENCES
Before minification:
angular.module(‘myApp’, []);
angular.module(‘myApp’)
.controller(‘myController’, myController);
function myController($scope, $timeout, myService) {
// some code goes here
}
After:
angular.module(‘myApp’,[]);angular.module(‘myApp’).controller(‘myContro
ller’,myController);function myController(l,o,p){...}
SOLUTIONS
Inline array annotation
$inject property annotation
angular.module(‘myApp’)
.controller(‘myController’, [‘$scope’, ‘myService’, myController]);
function myController($scope, myService) {
...
}
angular.module(‘myApp’).controller(‘myController’, myController);
myController.$inject = [‘$scope’, ‘myService’];
function myController($scope, myService) {
...
}
ОЙ, ВСЕ!

More Related Content

PPTX
AngularJS Services
PPTX
AngularJS Directives
PPTX
AngularJS Routing
PPTX
AngulrJS Overview
PPTX
AngularJS Compile Process
PPTX
AngularJS $Provide Service
PPTX
AngularJS Architecture
PPTX
AngularJS - $http & $resource Services
AngularJS Services
AngularJS Directives
AngularJS Routing
AngulrJS Overview
AngularJS Compile Process
AngularJS $Provide Service
AngularJS Architecture
AngularJS - $http & $resource Services

What's hot (20)

PPTX
Component lifecycle hooks in Angular 2.0
PDF
Angular js - 4developers 12 kwietnia 2013
PDF
AngularJs
PPTX
Workshop 1: Good practices in JavaScript
PDF
JavaScript patterns
PDF
Workshop 5: JavaScript testing
PDF
Javascript: the important bits
PDF
Design Patterns in PHP5
PDF
05 JavaScript #burningkeyboards
PDF
Min-Maxing Software Costs
PDF
GDayX - Advanced Angular.JS
PDF
06 jQuery #burningkeyboards
PDF
Min-Maxing Software Costs - Laracon EU 2015
PPTX
PDF
Angular promises and http
PDF
Hacking Movable Type
PPTX
AngularJs $provide API internals & circular dependency problem.
PDF
Decoupling with Design Patterns and Symfony2 DIC
PDF
Intro to Angular.JS Directives
Component lifecycle hooks in Angular 2.0
Angular js - 4developers 12 kwietnia 2013
AngularJs
Workshop 1: Good practices in JavaScript
JavaScript patterns
Workshop 5: JavaScript testing
Javascript: the important bits
Design Patterns in PHP5
05 JavaScript #burningkeyboards
Min-Maxing Software Costs
GDayX - Advanced Angular.JS
06 jQuery #burningkeyboards
Min-Maxing Software Costs - Laracon EU 2015
Angular promises and http
Hacking Movable Type
AngularJs $provide API internals & circular dependency problem.
Decoupling with Design Patterns and Symfony2 DIC
Intro to Angular.JS Directives
Ad

Viewers also liked (17)

PDF
Pre report-pl
PDF
Midagon - presentation
PPT
Paskaita nr2 klasifikavimas
PPTX
Engaging citizens
PPTX
Propel Ad - DDM Alliance Summit Marketing on Facebook
PPTX
Graduate Marketing Association(GMARK)2015 2016 General Meeting Presentation
PPT
Defensem els animals
PPTX
Marin Software - DDM Alliance Summit Marketing on Facebook
PPTX
2014 Benefit Concert Sponsor
PDF
Odf report-destruction-of-independent-journalism-in-ukraine-ru 1
PPTX
PDF
Doc092
PPTX
TradeSmart Webinar 11-24-15 slideshare
PDF
Odf sprawozdanie finansowe_2009
PPTX
WEEE Recycling
DOCX
Hướng dẫn kết nối máy chấm công với máy tính
PDF
Financial report 2011 eng
Pre report-pl
Midagon - presentation
Paskaita nr2 klasifikavimas
Engaging citizens
Propel Ad - DDM Alliance Summit Marketing on Facebook
Graduate Marketing Association(GMARK)2015 2016 General Meeting Presentation
Defensem els animals
Marin Software - DDM Alliance Summit Marketing on Facebook
2014 Benefit Concert Sponsor
Odf report-destruction-of-independent-journalism-in-ukraine-ru 1
Doc092
TradeSmart Webinar 11-24-15 slideshare
Odf sprawozdanie finansowe_2009
WEEE Recycling
Hướng dẫn kết nối máy chấm công với máy tính
Financial report 2011 eng
Ad

Similar to AngularJS: what is underneath the hood (20)

PPTX
Optimizing Angular Performance in Enterprise Single Page Apps
PDF
Writing Maintainable JavaScript
PPTX
AngularJS, More Than Directives !
PDF
Clean Javascript
PDF
Introduction to Zend Framework web services
PDF
Ten useful JavaScript tips & best practices
PDF
jQuery secrets
PDF
ZF2 for the ZF1 Developer
PDF
Angular Performance: Then, Now and the Future. Todd Motto
PDF
international PHP2011_Bastian Feder_jQuery's Secrets
PDF
Inversion Of Control
KEY
Zend framework service
KEY
Zend framework service
PDF
Hands on AngularJS
PPTX
Angular Workshop_Sarajevo2
PDF
Symfony2 from the Trenches
PDF
How Kris Writes Symfony Apps
PDF
Backbone Basics with Examples
PDF
JavaScript Fundamentals with Angular and Lodash
PDF
Get AngularJS Started!
Optimizing Angular Performance in Enterprise Single Page Apps
Writing Maintainable JavaScript
AngularJS, More Than Directives !
Clean Javascript
Introduction to Zend Framework web services
Ten useful JavaScript tips & best practices
jQuery secrets
ZF2 for the ZF1 Developer
Angular Performance: Then, Now and the Future. Todd Motto
international PHP2011_Bastian Feder_jQuery's Secrets
Inversion Of Control
Zend framework service
Zend framework service
Hands on AngularJS
Angular Workshop_Sarajevo2
Symfony2 from the Trenches
How Kris Writes Symfony Apps
Backbone Basics with Examples
JavaScript Fundamentals with Angular and Lodash
Get AngularJS Started!

More from DA-14 (12)

PPTX
Express js clean-controller
PPTX
Express js api-versioning
PPTX
Tech talk Angular 2
PPTX
Firebase not really_yohoho
PDF
Techtalk#8: Design patterns in real life
PPTX
Techtalk#7: Architecture principles by Steve McConnell's book "Code Complete"
PPTX
Mysql, MongoDb feat. Doctrine2
PPTX
Web Components: back to the future
PPTX
Techtalk#6: NodeJs: pitfalls (based on game project)
PPTX
JS Frameworks Day April,26 of 2014
PDF
TechTalk#2: Принципы управления временем
PDF
TechTalk#3: REST
Express js clean-controller
Express js api-versioning
Tech talk Angular 2
Firebase not really_yohoho
Techtalk#8: Design patterns in real life
Techtalk#7: Architecture principles by Steve McConnell's book "Code Complete"
Mysql, MongoDb feat. Doctrine2
Web Components: back to the future
Techtalk#6: NodeJs: pitfalls (based on game project)
JS Frameworks Day April,26 of 2014
TechTalk#2: Принципы управления временем
TechTalk#3: REST

Recently uploaded (20)

PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
System and Network Administraation Chapter 3
PPT
Introduction Database Management System for Course Database
PPTX
ai tools demonstartion for schools and inter college
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
CHAPTER 2 - PM Management and IT Context
PPTX
history of c programming in notes for students .pptx
PDF
System and Network Administration Chapter 2
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
medical staffing services at VALiNTRY
PPTX
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PPTX
ISO 45001 Occupational Health and Safety Management System
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PPTX
Transform Your Business with a Software ERP System
Adobe Illustrator 28.6 Crack My Vision of Vector Design
System and Network Administraation Chapter 3
Introduction Database Management System for Course Database
ai tools demonstartion for schools and inter college
Which alternative to Crystal Reports is best for small or large businesses.pdf
CHAPTER 2 - PM Management and IT Context
history of c programming in notes for students .pptx
System and Network Administration Chapter 2
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 41
medical staffing services at VALiNTRY
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
ISO 45001 Occupational Health and Safety Management System
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
How to Choose the Right IT Partner for Your Business in Malaysia
ManageIQ - Sprint 268 Review - Slide Deck
Transform Your Business with a Software ERP System

AngularJS: what is underneath the hood

  • 2. - the less routine code the happier developers - good application structure two-way data binding - directives - testability - active community / cool documentation, etc...
  • 3. var btn = document.getElementById("myBtn"); btn.addEventListener("click", onClick); function onClick(evt) { // some code }
  • 4. <button ng-click=”onClick($event)”></button> element.on(‘click’, function(event){ var callback = function(){ fn(scope, {$event: event}); } scope.$apply(callback); })
  • 5. <span>{{myModel}}</span> function myController($scope, $timeout) { $scope.myModel = ‘value1’; setTimeout(function(){ $scope.myModel = ‘value2’; }, 500); $timeout(function(){ $scope.myModel = ‘value2’; }, 500); }
  • 6. scope.$watch(‘someModel2’, callback); {{someModel}}, ng-bind ng-repeat, ng-model.. $timeout(fn) с нулевой задержкой scope.$evalAsync(fn) $watch list $evalAsync list
  • 7. step 1: function Scope() { } step 2: function Scope() { this.$$watchers = []; } step 3: Scope.prototype.$watch = function(watchFn, listenerFn) { var watcher = { watchFn: watchFn, listenerFn: listenerFn }; this.$$watchers.push(watcher); }; $watchList implementation
  • 8. step 4: Scope.prototype.$digest = function() { _.forEach(this.$$watchers, function(watch) { watch.listenerFn(); }); }; step 5: Scope.prototype.$digest = function() { var self = this; _.forEach(this.$$watchers, function(watch) { var newValue = watch.watchFn(self); var oldValue = watch.last; if (newValue !== oldValue) { watch.listenerFn(newValue, oldValue, self); } watch.last = newValue; }); };
  • 9. ... $scope.$watch(‘myModel’, function(){ alert(‘My model was changed’); }); $scope.$watch(‘yourModel’, function(){ scope.myModel = ‘someValue’; }); ... <input type=”text” ng-model=”yourModel” />
  • 10. Scope.prototype.$digest = function() { var self = this; var dirty; do { dirty = false; _.forEach(this.$$watchers, function(watch) { var newValue = watch.watchFn(self); var oldValue = watch.last; if (newValue !== oldValue) { watch.listenerFn(newValue, oldValue, self); dirty = true; } watch.last = newValue; }); } while (dirty); }; DIRTY CHECK
  • 11. step 1: function Scope() { this.$$watchers = []; this.$$asyncQueue = []; } step 2: Scope.prototype.$evalAsync = function(expr) { var obj = {scope: this, expression: expr}; this.$$asyncQueue.push(obj); }; step 3: Scope.prototype.$digest = function() { while (this.$$asyncQueue.length) { var asyncTask = this.$$asyncQueue.shift(); this.$eval(asyncTask.expression); } ... }; $watchList implementation$evalAsync implementation function myCtrl($scope, $rootScope) { $scope.myModel = ‘value1’; $scope.$evalAsync(function() { console.log($scope.myModel); }); $scope.myModel = ‘value2’; }
  • 12. $scope.$apply vs $scope.$digest <body ng-app=”myApp”>{{rootMessage}} <div ng-controller=”myCtrl”>{{childMessage}}</div> </body> function myCtrl($scope, $rootScope) { $rootScope.rootMessage = ‘root message’; $scope.childMessage = ‘child message’; setTimeout(function(){ $rootScope.rootMessage = ‘new root message’; $scope.childMessage = ‘new child message’; $scope.apply(); // both model are re-rendered $scope.digest(); // only childMessage }, 5000); }
  • 13. setTimeout(function(){ $scope.apply(function(){//some code}); }, 5000); } $apply: function(expr) { try { return this.$eval(expr); } catch (e) { $exceptionHandler(e); } finally { try { $rootScope.$digest(); } catch (e) { $exceptionHandler(e); throw e; } }}
  • 14. SOME OPTIMIZATION TIPS - minimize watchers: - limit DOM filters - use onetime binding when possible ng-bind=”::myModel” ng- repeat=”item in ::items” or bindonce if Angular < 1.3 - lightweight watch-functions and callbacks in watchers - ng-repeat=”item in items track by item.id” - $watchCollection instead of $watch with 3rd parameter equaled true - debounce ng-model <input ng-model=”myModel” ng-model- options=”{debounce: 500}” /> - use native JS or lodash (for example, simple ‘for’ loop instead of angular.forEach ) - use directive ng-bind instead of {{}};
  • 15. $parse $scope.$watch(function() { return $scope.myModel; }, callback); $scope.$watch(‘myModel’, callback); $watch: function(watchExp, listener, objectEquality){ var get = $parse(watchExp);... } $eval: function(expr, locals) { return $parse(expr)(this, locals); },
  • 16. DEPENDENCY INJECTION IN ANGULAR Dependency Injection is a software design pattern in which an object is given its dependencies, rather than the object creating them itself. angular.module(‘myApp’, []); angular.module(‘myApp’) .controller(‘myController’, myController); function myController($scope, $timeout, myService) { // some code goes here } function myController($timeout, $scope, myService) { // some code goes here }
  • 17. ISSUES WITH IMPLICIT DEPENDENCES Before minification: angular.module(‘myApp’, []); angular.module(‘myApp’) .controller(‘myController’, myController); function myController($scope, $timeout, myService) { // some code goes here } After: angular.module(‘myApp’,[]);angular.module(‘myApp’).controller(‘myContro ller’,myController);function myController(l,o,p){...}
  • 18. SOLUTIONS Inline array annotation $inject property annotation angular.module(‘myApp’) .controller(‘myController’, [‘$scope’, ‘myService’, myController]); function myController($scope, myService) { ... } angular.module(‘myApp’).controller(‘myController’, myController); myController.$inject = [‘$scope’, ‘myService’]; function myController($scope, myService) { ... }