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) {
...
}
ОЙ, ВСЕ!
Ad

More Related Content

What's hot (20)

Javascript - Beyond-jQuery
Javascript - Beyond-jQueryJavascript - Beyond-jQuery
Javascript - Beyond-jQuery
Tanner Moushey ❖ Mission Lab - WordPress Agency
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
Eyal Vardi
 
Angular js - 4developers 12 kwietnia 2013
Angular js - 4developers 12 kwietnia 2013Angular js - 4developers 12 kwietnia 2013
Angular js - 4developers 12 kwietnia 2013
Marcin Wosinek
 
AngularJs
AngularJsAngularJs
AngularJs
Hossein Baghayi
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
Visual Engineering
 
JavaScript patterns
JavaScript patternsJavaScript patterns
JavaScript patterns
Norihito YAMAKAWA
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
Visual Engineering
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
Chris Saylor
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5
Wildan Maulana
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards
Denis Ristic
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
Konstantin Kudryashov
 
GDayX - Advanced Angular.JS
GDayX - Advanced Angular.JSGDayX - Advanced Angular.JS
GDayX - Advanced Angular.JS
Nicolas Embleton
 
06 jQuery #burningkeyboards
06 jQuery  #burningkeyboards06 jQuery  #burningkeyboards
06 jQuery #burningkeyboards
Denis Ristic
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015
Konstantin Kudryashov
 
Bacbkone js
Bacbkone jsBacbkone js
Bacbkone js
Артём Курапов
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
Alexe Bogdan
 
Hacking Movable Type
Hacking Movable TypeHacking Movable Type
Hacking Movable Type
Stefano Rodighiero
 
AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.
Yan Yankowski
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DIC
Konstantin Kudryashov
 
Intro to Angular.JS Directives
Intro to Angular.JS DirectivesIntro to Angular.JS Directives
Intro to Angular.JS Directives
Christian Lilley
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
Eyal Vardi
 
Angular js - 4developers 12 kwietnia 2013
Angular js - 4developers 12 kwietnia 2013Angular js - 4developers 12 kwietnia 2013
Angular js - 4developers 12 kwietnia 2013
Marcin Wosinek
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
Visual Engineering
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
Visual Engineering
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
Chris Saylor
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5
Wildan Maulana
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards
Denis Ristic
 
GDayX - Advanced Angular.JS
GDayX - Advanced Angular.JSGDayX - Advanced Angular.JS
GDayX - Advanced Angular.JS
Nicolas Embleton
 
06 jQuery #burningkeyboards
06 jQuery  #burningkeyboards06 jQuery  #burningkeyboards
06 jQuery #burningkeyboards
Denis Ristic
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015
Konstantin Kudryashov
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
Alexe Bogdan
 
AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.
Yan Yankowski
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DIC
Konstantin Kudryashov
 
Intro to Angular.JS Directives
Intro to Angular.JS DirectivesIntro to Angular.JS Directives
Intro to Angular.JS Directives
Christian Lilley
 

Viewers also liked (17)

Midagon - presentation
Midagon - presentationMidagon - presentation
Midagon - presentation
Martin Ivanov
 
Paskaita nr2 klasifikavimas
Paskaita nr2 klasifikavimasPaskaita nr2 klasifikavimas
Paskaita nr2 klasifikavimas
Donatas Bukelis
 
Engaging citizens
Engaging citizensEngaging citizens
Engaging citizens
Janix Joy
 
Propel Ad - DDM Alliance Summit Marketing on Facebook
Propel Ad - DDM Alliance Summit Marketing on FacebookPropel Ad - DDM Alliance Summit Marketing on Facebook
Propel Ad - DDM Alliance Summit Marketing on Facebook
DDM Alliance
 
Graduate Marketing Association(GMARK)2015 2016 General Meeting Presentation
Graduate Marketing Association(GMARK)2015 2016 General Meeting PresentationGraduate Marketing Association(GMARK)2015 2016 General Meeting Presentation
Graduate Marketing Association(GMARK)2015 2016 General Meeting Presentation
Shilpa Mohanty
 
Defensem els animals
Defensem els animals Defensem els animals
Defensem els animals
martita56
 
Marin Software - DDM Alliance Summit Marketing on Facebook
Marin Software - DDM Alliance Summit Marketing on FacebookMarin Software - DDM Alliance Summit Marketing on Facebook
Marin Software - DDM Alliance Summit Marketing on Facebook
DDM Alliance
 
2014 Benefit Concert Sponsor
2014 Benefit Concert Sponsor2014 Benefit Concert Sponsor
2014 Benefit Concert Sponsor
smberry
 
Odf report-destruction-of-independent-journalism-in-ukraine-ru 1
Odf report-destruction-of-independent-journalism-in-ukraine-ru 1Odf report-destruction-of-independent-journalism-in-ukraine-ru 1
Odf report-destruction-of-independent-journalism-in-ukraine-ru 1
odfoundation
 
Burabod
BurabodBurabod
Burabod
Franz Muhlfeld
 
Doc092
Doc092Doc092
Doc092
odfoundation
 
TradeSmart Webinar 11-24-15 slideshare
TradeSmart Webinar 11-24-15 slideshareTradeSmart Webinar 11-24-15 slideshare
TradeSmart Webinar 11-24-15 slideshare
Relational Solutions a Mindtree Company
 
Odf sprawozdanie finansowe_2009
Odf sprawozdanie finansowe_2009Odf sprawozdanie finansowe_2009
Odf sprawozdanie finansowe_2009
odfoundation
 
WEEE Recycling
WEEE RecyclingWEEE Recycling
WEEE Recycling
Minds Ahead
 
Hướng dẫn kết nối máy chấm công với máy tính
Hướng dẫn kết nối máy chấm công với máy tínhHướng dẫn kết nối máy chấm công với máy tính
Hướng dẫn kết nối máy chấm công với máy tính
giaiphapchamcong
 
Financial report 2011 eng
Financial report 2011   engFinancial report 2011   eng
Financial report 2011 eng
odfoundation
 
Midagon - presentation
Midagon - presentationMidagon - presentation
Midagon - presentation
Martin Ivanov
 
Paskaita nr2 klasifikavimas
Paskaita nr2 klasifikavimasPaskaita nr2 klasifikavimas
Paskaita nr2 klasifikavimas
Donatas Bukelis
 
Engaging citizens
Engaging citizensEngaging citizens
Engaging citizens
Janix Joy
 
Propel Ad - DDM Alliance Summit Marketing on Facebook
Propel Ad - DDM Alliance Summit Marketing on FacebookPropel Ad - DDM Alliance Summit Marketing on Facebook
Propel Ad - DDM Alliance Summit Marketing on Facebook
DDM Alliance
 
Graduate Marketing Association(GMARK)2015 2016 General Meeting Presentation
Graduate Marketing Association(GMARK)2015 2016 General Meeting PresentationGraduate Marketing Association(GMARK)2015 2016 General Meeting Presentation
Graduate Marketing Association(GMARK)2015 2016 General Meeting Presentation
Shilpa Mohanty
 
Defensem els animals
Defensem els animals Defensem els animals
Defensem els animals
martita56
 
Marin Software - DDM Alliance Summit Marketing on Facebook
Marin Software - DDM Alliance Summit Marketing on FacebookMarin Software - DDM Alliance Summit Marketing on Facebook
Marin Software - DDM Alliance Summit Marketing on Facebook
DDM Alliance
 
2014 Benefit Concert Sponsor
2014 Benefit Concert Sponsor2014 Benefit Concert Sponsor
2014 Benefit Concert Sponsor
smberry
 
Odf report-destruction-of-independent-journalism-in-ukraine-ru 1
Odf report-destruction-of-independent-journalism-in-ukraine-ru 1Odf report-destruction-of-independent-journalism-in-ukraine-ru 1
Odf report-destruction-of-independent-journalism-in-ukraine-ru 1
odfoundation
 
Odf sprawozdanie finansowe_2009
Odf sprawozdanie finansowe_2009Odf sprawozdanie finansowe_2009
Odf sprawozdanie finansowe_2009
odfoundation
 
Hướng dẫn kết nối máy chấm công với máy tính
Hướng dẫn kết nối máy chấm công với máy tínhHướng dẫn kết nối máy chấm công với máy tính
Hướng dẫn kết nối máy chấm công với máy tính
giaiphapchamcong
 
Financial report 2011 eng
Financial report 2011   engFinancial report 2011   eng
Financial report 2011 eng
odfoundation
 
Ad

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

Optimizing Angular Performance in Enterprise Single Page Apps
Optimizing Angular Performance in Enterprise Single Page AppsOptimizing Angular Performance in Enterprise Single Page Apps
Optimizing Angular Performance in Enterprise Single Page Apps
Morgan Stone
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
Andrew Dupont
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !
Gaurav Behere
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
Ryunosuke SATO
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web services
Michelangelo van Dam
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
Ankit Rastogi
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
Bastian Feder
 
ZF2 for the ZF1 Developer
ZF2 for the ZF1 DeveloperZF2 for the ZF1 Developer
ZF2 for the ZF1 Developer
Gary Hockin
 
Angular Performance: Then, Now and the Future. Todd Motto
Angular Performance: Then, Now and the Future. Todd MottoAngular Performance: Then, Now and the Future. Todd Motto
Angular Performance: Then, Now and the Future. Todd Motto
Future Insights
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
smueller_sandsmedia
 
Inversion Of Control
Inversion Of ControlInversion Of Control
Inversion Of Control
Chad Hietala
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
Michelangelo van Dam
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
Michelangelo van Dam
 
Hands on AngularJS
Hands on AngularJSHands on AngularJS
Hands on AngularJS
Thomas Fankhauser
 
Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2
Christoffer Noring
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
Jonathan Wage
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
Kris Wallsmith
 
Backbone Basics with Examples
Backbone Basics with ExamplesBackbone Basics with Examples
Backbone Basics with Examples
Sergey Bolshchikov
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
Bret Little
 
Get AngularJS Started!
Get AngularJS Started!Get AngularJS Started!
Get AngularJS Started!
Dzmitry Ivashutsin
 
Optimizing Angular Performance in Enterprise Single Page Apps
Optimizing Angular Performance in Enterprise Single Page AppsOptimizing Angular Performance in Enterprise Single Page Apps
Optimizing Angular Performance in Enterprise Single Page Apps
Morgan Stone
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
Andrew Dupont
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !
Gaurav Behere
 
Introduction to Zend Framework web services
Introduction to Zend Framework web servicesIntroduction to Zend Framework web services
Introduction to Zend Framework web services
Michelangelo van Dam
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
Ankit Rastogi
 
ZF2 for the ZF1 Developer
ZF2 for the ZF1 DeveloperZF2 for the ZF1 Developer
ZF2 for the ZF1 Developer
Gary Hockin
 
Angular Performance: Then, Now and the Future. Todd Motto
Angular Performance: Then, Now and the Future. Todd MottoAngular Performance: Then, Now and the Future. Todd Motto
Angular Performance: Then, Now and the Future. Todd Motto
Future Insights
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
smueller_sandsmedia
 
Inversion Of Control
Inversion Of ControlInversion Of Control
Inversion Of Control
Chad Hietala
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
Jonathan Wage
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
Kris Wallsmith
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
Bret Little
 
Ad

More from DA-14 (12)

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

Recently uploaded (20)

Digital Twins Software Service in Belfast
Digital Twins Software Service in BelfastDigital Twins Software Service in Belfast
Digital Twins Software Service in Belfast
julia smits
 
sequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineeringsequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineering
aashrithakondapalli8
 
[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts
Dimitrios Platis
 
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business StageA Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
SynapseIndia
 
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.pptPassive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
IES VE
 
Adobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 linkAdobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 link
mahmadzubair09
 
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdfTop Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
evrigsolution
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
AEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural MeetingAEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural Meeting
jennaf3
 
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
Ranking Google
 
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptxThe-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
james brownuae
 
Do not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your causeDo not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your cause
Fexle Services Pvt. Ltd.
 
Medical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk ScoringMedical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk Scoring
ICS
 
Beyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraftBeyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraft
Dmitrii Ivanov
 
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studiesTroubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Tier1 app
 
Why Tapitag Ranks Among the Best Digital Business Card Providers
Why Tapitag Ranks Among the Best Digital Business Card ProvidersWhy Tapitag Ranks Among the Best Digital Business Card Providers
Why Tapitag Ranks Among the Best Digital Business Card Providers
Tapitag
 
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
How I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetryHow I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetry
Cees Bos
 
What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?
HireME
 
How to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryErrorHow to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryError
Tier1 app
 
Digital Twins Software Service in Belfast
Digital Twins Software Service in BelfastDigital Twins Software Service in Belfast
Digital Twins Software Service in Belfast
julia smits
 
sequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineeringsequencediagrams.pptx software Engineering
sequencediagrams.pptx software Engineering
aashrithakondapalli8
 
[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts[gbgcpp] Let's get comfortable with concepts
[gbgcpp] Let's get comfortable with concepts
Dimitrios Platis
 
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business StageA Comprehensive Guide to CRM Software Benefits for Every Business Stage
A Comprehensive Guide to CRM Software Benefits for Every Business Stage
SynapseIndia
 
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.pptPassive House Canada Conference 2025 Presentation [Final]_v4.ppt
Passive House Canada Conference 2025 Presentation [Final]_v4.ppt
IES VE
 
Adobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 linkAdobe InDesign Crack FREE Download 2025 link
Adobe InDesign Crack FREE Download 2025 link
mahmadzubair09
 
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdfTop Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
Top Magento Hyvä Theme Features That Make It Ideal for E-commerce.pdf
evrigsolution
 
Exchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv SoftwareExchange Migration Tool- Shoviv Software
Exchange Migration Tool- Shoviv Software
Shoviv Software
 
AEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural MeetingAEM User Group DACH - 2025 Inaugural Meeting
AEM User Group DACH - 2025 Inaugural Meeting
jennaf3
 
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
!%& IDM Crack with Internet Download Manager 6.42 Build 32 >
Ranking Google
 
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptxThe-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
The-Future-is-Hybrid-Exploring-Azure’s-Role-in-Multi-Cloud-Strategies.pptx
james brownuae
 
Do not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your causeDo not let staffing shortages and limited fiscal view hamper your cause
Do not let staffing shortages and limited fiscal view hamper your cause
Fexle Services Pvt. Ltd.
 
Medical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk ScoringMedical Device Cybersecurity Threat & Risk Scoring
Medical Device Cybersecurity Threat & Risk Scoring
ICS
 
Beyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraftBeyond the code. Complexity - 2025.05 - SwiftCraft
Beyond the code. Complexity - 2025.05 - SwiftCraft
Dmitrii Ivanov
 
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studiesTroubleshooting JVM Outages – 3 Fortune 500 case studies
Troubleshooting JVM Outages – 3 Fortune 500 case studies
Tier1 app
 
Why Tapitag Ranks Among the Best Digital Business Card Providers
Why Tapitag Ranks Among the Best Digital Business Card ProvidersWhy Tapitag Ranks Among the Best Digital Business Card Providers
Why Tapitag Ranks Among the Best Digital Business Card Providers
Tapitag
 
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World ExamplesMastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
Mastering Selenium WebDriver: A Comprehensive Tutorial with Real-World Examples
jamescantor38
 
How I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetryHow I solved production issues with OpenTelemetry
How I solved production issues with OpenTelemetry
Cees Bos
 
What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?What Do Candidates Really Think About AI-Powered Recruitment Tools?
What Do Candidates Really Think About AI-Powered Recruitment Tools?
HireME
 
How to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryErrorHow to Troubleshoot 9 Types of OutOfMemoryError
How to Troubleshoot 9 Types of OutOfMemoryError
Tier1 app
 

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) { ... }
  翻译: