SlideShare a Scribd company logo
AngularJS, More Than Directives!
- Gaurav Behere
- http://www.gauravbehere.in
Topics Covered
A. Apply/Digest Phase Cycle.
B. Handling Memory.
C. Transclusion.
D. Promises.
E. Watch.
Apply/Digest Cycle
$digest:
$digest processes all the watch-Expressions for the current scope and its children
What happens when a watch-Expression is processed?
The value of the current watch-Expression is compared with the value of the previous
watch-Expression, and if they do not match then it is “dirty” and a listener is fired.
This is what we call as “Dirty Checking”.
Angular doesn’t directly call $digest(). Instead, it calls $scope.$apply(), which in turn calls
$rootScope.$digest(). As a result of this, a digest cycle starts at the $rootScope, and
subsequently visits all the child scopes calling the watchers along the way.
Now, let’s assume you attach an ng-click directive to a button and pass a function name to
it. When the button is clicked, AngularJS wraps the function call within $scope.$apply(). So,
your function executes as usual, change models (if any), and a $digest cycle starts to
ensure your changes are reflected in the view.
When & why should I call apply() manually ?
When an external event (such as a user action, timer or XHR) is received, the associated
expression must be applied to the scope through the $apply() method so that all listeners
are updated correctly.
It will account for only those model changes which are done inside AngularJS’ context (i.e.
the code that changes models is wrapped inside $apply()). Angular’s built-in directives
already do this so that any model changes you make are reflected in the view. However, if
you change any model outside of the Angular context, then you need to inform Angular of
the changes by calling $apply() manually. It’s like telling Angular that you are changing
some models and it should fire the watchers so that your changes propagate properly.
For example, if you use JavaScript’s setTimeout() function to update a scope model,
Angular has no way of knowing what you might change. In this case it’s your responsibility
to call $apply() manually, which triggers a $digest cycle. Similarly, if you have a directive
that sets up a DOM event listener and changes some models inside the handler function,
you need to call $apply() to ensure the changes take effect
Example
If you use JavaScript’s setTimeout() function to update a scope model, Angular has no way of
knowing what you might change. In this case it’s your responsibility to call $apply() manually,
which triggers a $digest cycle.
HTML
<body ng-app="myApp">
<div ng-controller="MessageController"> Delayed Message: {{message}} </div>
</body>
JS /*Without Apply*/
angular.module('myApp',[]).controller('MessageController', function($scope) {
$scope.getMessage = function() {
setTimeout(function() {
$scope.message = 'Fetched after 3 seconds';
}, 2000);
$scope.getMessage();
}
JS /*With Apply*/
angular.module('myApp',[]).controller('MessageController', function($scope) {
$scope.getMessage = function() {
setTimeout(function() {
$scope.$apply(function() {
$scope.message = 'Fetched after 3 seconds';
});
}, 2000);
}
$scope.getMessage();
});
Handling Memory
$destroy()
Removes the current scope (and all of its children) from the parent scope. Removal implies
that calls to $digest() will no longer propagate to the current scope and its children. Removal
also implies that the current scope is eligible for garbage collection.
The $destroy() is usually used by directives such as ngRepeat for managing the unrolling of
the loop.
Just before a scope is destroyed a $destroy event is broadcasted on this scope. Application
code can register a $destroy event handler that will give it chance to perform any necessary
clean-up.
Scope.$destroy();
Calling $destroy() on a scope causes an event “$destroy” to flow downstream.
Why & when should I manually handle memory ?
If you are using timers to update scope.
In cases where you have event listeners.
As an example, the following controller continuously updates a model value in one second intervals, and these updates
will continue forever, even after the controller’s view is gone and the scope is removed from its parent.
module.controller("TestController", function($scope, $timeout) {
var onTimeout = function() {
$scope.value += 1;
$timeout(onTimeout, 1000);
};
$timeout(onTimeout, 1000);
$scope.value = 0;
});
Listening for the $destroy event is an opportunity to halt the timer
module.controller("TestController", function($scope, $timeout) {
var onTimeout = function() {
$scope.value += 1;
timer = $timeout(onTimeout, 1000);
};
var timer = $timeout(onTimeout, 1000);
$scope.value = 0;
$scope.$on("$destroy", function() {
if (timer) {
$timeout.cancel(timer);
}
});
});
Promises
The AngularJS $q service is said to be inspired by Chris Kowal's Q library
(github.com/kriskowal/q). The library's goal is to allow users to monitor asynchronous
progress by providing a "promise" as a return from a call. In AngularJS, the semantics of
using a promise are:
var promise = callThatRunsInBackground();
promise.then(
function(answer) {
// do something
},
function(error) {
// report something
},
function(progress) {
// report progress
});
A number of Angular services return promises: $http, $interval, $timeout, for example. All
promise returns are single objects; you're expected to research the service itself to find out
what it returns. For example, for $http.get, the promise returns an object with four
keys:data, status, headers, and config. Those are the same as the four parameters fed to the
success callback if you use those semantics:
// this
$http.get('/api/v1/movies/avengers')
.success(function(data, status, headers, config) {
$scope.movieContent = data;
});
// is the same as
var promise = $http.get('/api/v1/movies/avengers');
promise.then(
function(payload) {
$scope.movieContent = payload.data;
});
Deferring Promises, Defining Custom Promises:
function asyncGreet(name) {
var deferred = $q.defer();
setTimeout(function() {
deferred.notify('About to greet ' + name + '.');
if (okToGreet(name)) {
deferred.resolve('Hello, ' + name + '!');
} else {
deferred.reject('Greeting ' + name + ' is not allowed.');
}
}, 1000);
return deferred.promise;
}
var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
alert('Success: ' + greeting);
}, function(reason) {
alert('Failed: ' + reason);
}, function(update) {
alert('Got notification: ' + update);
});
Chaining Promises
defer.promise
.then(function () {
alert("I promised I would show up");
})
.then(function () {
alert("me too");
})
.then(function () {
alert("and I");
});
defer.resolve();
It is also possible to resolve with parameters. The chained promises will cascade their return values to the
subsequent promise:
defer.promise
.then(function (weapon) {
alert("You can have my " + weapon);
return "bow";
})
.then(function (weapon) {
alert("And my " + weapon);
return "axe";
})
.then(function () {
alert("And my " + weapon);
});
defer.resolve("sword");
Transclusion
Transclusion provides a way for a consumer of a directive to define a template that is
imported into the directive and displayed. For example you might have a directive that
outputs a table while allowing the consumer of the directive to control how the table rows
are rendered. Or, you might have a directive that outputs an error message while allowing
the consumer of the directive to supply HTML content that handles rendering the error
using different colors. By supporting this type of functionality the consumer of the directive
has more control over how specific parts of the HTML generated by the directive are
rendered.
Two key features are provided by AngularJS to support transclusion. The first is a property
that is used in directives named transclude. When a directive supports transclusion this
property is set to true. The second is a directive named ng-transclude that is used to define
where external content will be placed in a directive’s template
Markup
<div ng-app="phoneApp">
<div ng-controller="AppCtrl">
<panel>
<div class="button">Click me!</div>
</panel>
</div>
</div>
var app = angular.module('phoneApp', []);
app.controller("AppCtrl", function ($scope) {
});
app.directive("panel", function () {
return {
restrict: "E",
template: '<div class="panel">This is a panel component</div>'
}
});
return {
restruct: "E",
transclude: true,
template: '<div class="panel" ng-transclude>This is a panel component </div>'
}
Watch
The $scope.watch() function creates a watch of some variable. When you register a watch you pass two functions
as parameters to the $watch() function:
A value function
A listener function
Here is an example:
$scope.$watch(function() {},
function() {}
);
The first function is the value function and the second function is the listener function.
The value function should return the value which is being watched. AngularJS can then check the value returned
against the value the watch function returned the last time. That way AngularJS can determine if the value has
changed. Here is an example:
$scope.$watch(function(scope) { return scope.data.myVar },
function() {}
);
This example value function returns the $scope variable scope.data.myVar. If the value of this variable changes, a
different value will be returned, and AngularJS will call the listener function.
The watchExpression is called on every call to $digest() and should return the value that will
be watched. (Since $digest() reruns when it detects changes the watchExpression can execute
multiple times per $digest() and should be idempotent.)
The listener is called only when the value from the current watchExpression and the previous
call to watchExpression are not equal (with the exception of the initial run, see below).
Inequality is determined according to reference inequality, strict comparison via the !==
Javascript operator, unless objectEquality == true (see next point)
When objectEquality == true, inequality of the watchExpression is determined according to
the angular.equals function. To save the value of the object for later comparison, the
angular.copy function is used. This therefore means that watching complex objects will have
adverse memory and performance implications.
The watch listener may change the model, which may trigger other listeners to fire. This is
achieved by rerunning the watchers until no changes are detected. The rerun iteration limit is
10 to prevent an infinite loop deadlock.
Further Read/References
https://docs.angularjs.org/api/ng/type/$rootScope.Scope
https://thinkster.io/egghead/promises/
http://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls/
http://andyshora.com/promises-angularjs-explained-as-cartoon.html

More Related Content

What's hot

描画とビジネスをクリーンに分ける(公開用)
描画とビジネスをクリーンに分ける(公開用)描画とビジネスをクリーンに分ける(公開用)
描画とビジネスをクリーンに分ける(公開用)
Kenji Tanaka
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS Services
Eyal Vardi
 
Angular Tutorial Freshers and Experienced
Angular Tutorial Freshers and ExperiencedAngular Tutorial Freshers and Experienced
Angular Tutorial Freshers and Experienced
rajkamaltibacademy
 
What the FUF?
What the FUF?What the FUF?
What the FUF?
An Doan
 
AngularJS: what is underneath the hood
AngularJS: what is underneath the hood AngularJS: what is underneath the hood
AngularJS: what is underneath the hood
DA-14
 
AngularJS $Provide Service
AngularJS $Provide ServiceAngularJS $Provide Service
AngularJS $Provide Service
Eyal Vardi
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projects
Ignacio Martín
 
Inversion Of Control
Inversion Of ControlInversion Of Control
Inversion Of Control
Chad Hietala
 
Owl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOwl: The New Odoo UI Framework
Owl: The New Odoo UI Framework
Odoo
 
Angular js routing options
Angular js routing optionsAngular js routing options
Angular js routing options
Nir Kaufman
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
Knoldus Inc.
 
06 jQuery #burningkeyboards
06 jQuery  #burningkeyboards06 jQuery  #burningkeyboards
06 jQuery #burningkeyboards
Denis Ristic
 
jQuery for Beginners
jQuery for Beginners jQuery for Beginners
jQuery for Beginners
NAILBITER
 
Ruby - Design patterns tdc2011
Ruby - Design patterns tdc2011Ruby - Design patterns tdc2011
Ruby - Design patterns tdc2011
Rafael Felix da Silva
 
Slightly Advanced Android Wear ;)
Slightly Advanced Android Wear ;)Slightly Advanced Android Wear ;)
Slightly Advanced Android Wear ;)
Alfredo Morresi
 
AngularJS Routing
AngularJS RoutingAngularJS Routing
AngularJS Routing
Eyal Vardi
 
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
 
Go Beast Mode with Realtime Reactive Interfaces in Angular 2 and Firebase
Go Beast Mode with Realtime Reactive Interfaces in Angular 2 and FirebaseGo Beast Mode with Realtime Reactive Interfaces in Angular 2 and Firebase
Go Beast Mode with Realtime Reactive Interfaces in Angular 2 and Firebase
Lukas Ruebbelke
 
Async Testing giving you a sinking feeling
Async Testing giving you a sinking feelingAsync Testing giving you a sinking feeling
Async Testing giving you a sinking feeling
Erin Zimmer
 
AngularJS Framework
AngularJS FrameworkAngularJS Framework
AngularJS Framework
Barcamp Saigon
 

What's hot (20)

描画とビジネスをクリーンに分ける(公開用)
描画とビジネスをクリーンに分ける(公開用)描画とビジネスをクリーンに分ける(公開用)
描画とビジネスをクリーンに分ける(公開用)
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS Services
 
Angular Tutorial Freshers and Experienced
Angular Tutorial Freshers and ExperiencedAngular Tutorial Freshers and Experienced
Angular Tutorial Freshers and Experienced
 
What the FUF?
What the FUF?What the FUF?
What the FUF?
 
AngularJS: what is underneath the hood
AngularJS: what is underneath the hood AngularJS: what is underneath the hood
AngularJS: what is underneath the hood
 
AngularJS $Provide Service
AngularJS $Provide ServiceAngularJS $Provide Service
AngularJS $Provide Service
 
Integrating React.js with PHP projects
Integrating React.js with PHP projectsIntegrating React.js with PHP projects
Integrating React.js with PHP projects
 
Inversion Of Control
Inversion Of ControlInversion Of Control
Inversion Of Control
 
Owl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOwl: The New Odoo UI Framework
Owl: The New Odoo UI Framework
 
Angular js routing options
Angular js routing optionsAngular js routing options
Angular js routing options
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
06 jQuery #burningkeyboards
06 jQuery  #burningkeyboards06 jQuery  #burningkeyboards
06 jQuery #burningkeyboards
 
jQuery for Beginners
jQuery for Beginners jQuery for Beginners
jQuery for Beginners
 
Ruby - Design patterns tdc2011
Ruby - Design patterns tdc2011Ruby - Design patterns tdc2011
Ruby - Design patterns tdc2011
 
Slightly Advanced Android Wear ;)
Slightly Advanced Android Wear ;)Slightly Advanced Android Wear ;)
Slightly Advanced Android Wear ;)
 
AngularJS Routing
AngularJS RoutingAngularJS Routing
AngularJS Routing
 
Workshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScriptWorkshop 1: Good practices in JavaScript
Workshop 1: Good practices in JavaScript
 
Go Beast Mode with Realtime Reactive Interfaces in Angular 2 and Firebase
Go Beast Mode with Realtime Reactive Interfaces in Angular 2 and FirebaseGo Beast Mode with Realtime Reactive Interfaces in Angular 2 and Firebase
Go Beast Mode with Realtime Reactive Interfaces in Angular 2 and Firebase
 
Async Testing giving you a sinking feeling
Async Testing giving you a sinking feelingAsync Testing giving you a sinking feeling
Async Testing giving you a sinking feeling
 
AngularJS Framework
AngularJS FrameworkAngularJS Framework
AngularJS Framework
 

Viewers also liked

План дій з реформування підприємств установ
План дій з реформування підприємств установПлан дій з реформування підприємств установ
План дій з реформування підприємств установ
Борис Гунько
 
0531 981 01 90 FULYA KİTAP ALANLAR-PLAK-KİTAP-ANTİKA EŞYA SATIN ALANLAR 0531 ...
0531 981 01 90 FULYA KİTAP ALANLAR-PLAK-KİTAP-ANTİKA EŞYA SATIN ALANLAR 0531 ...0531 981 01 90 FULYA KİTAP ALANLAR-PLAK-KİTAP-ANTİKA EŞYA SATIN ALANLAR 0531 ...
0531 981 01 90 FULYA KİTAP ALANLAR-PLAK-KİTAP-ANTİKA EŞYA SATIN ALANLAR 0531 ...
Antika Alanlar
 
Untitled presentation
Untitled presentationUntitled presentation
Untitled presentation
German Guaraca
 
0531 981 01 90 YALI KİTAP ALANLAR-PLAK-KİTAP-ANTİKA EŞYA SATIN ALANLAR 0531 9...
0531 981 01 90 YALI KİTAP ALANLAR-PLAK-KİTAP-ANTİKA EŞYA SATIN ALANLAR 0531 9...0531 981 01 90 YALI KİTAP ALANLAR-PLAK-KİTAP-ANTİKA EŞYA SATIN ALANLAR 0531 9...
0531 981 01 90 YALI KİTAP ALANLAR-PLAK-KİTAP-ANTİKA EŞYA SATIN ALANLAR 0531 9...
Antika Alanlar
 
Discurso Precade
Discurso PrecadeDiscurso Precade
Discurso Precade
IPAE
 
Review on Document Recommender Systems Using Hierarchical Clustering Techniques
Review on Document Recommender Systems Using Hierarchical Clustering TechniquesReview on Document Recommender Systems Using Hierarchical Clustering Techniques
Review on Document Recommender Systems Using Hierarchical Clustering Techniques
Association of Scientists, Developers and Faculties
 
Bar Modeling: Using Models to Help Solve Word Problems
Bar Modeling: Using Models to Help Solve Word ProblemsBar Modeling: Using Models to Help Solve Word Problems
Bar Modeling: Using Models to Help Solve Word Problems
erinmgardner
 
コンセプトアイデア 1
コンセプトアイデア 1コンセプトアイデア 1
コンセプトアイデア 1Jun Saeki
 

Viewers also liked (11)

План дій з реформування підприємств установ
План дій з реформування підприємств установПлан дій з реформування підприємств установ
План дій з реформування підприємств установ
 
0531 981 01 90 FULYA KİTAP ALANLAR-PLAK-KİTAP-ANTİKA EŞYA SATIN ALANLAR 0531 ...
0531 981 01 90 FULYA KİTAP ALANLAR-PLAK-KİTAP-ANTİKA EŞYA SATIN ALANLAR 0531 ...0531 981 01 90 FULYA KİTAP ALANLAR-PLAK-KİTAP-ANTİKA EŞYA SATIN ALANLAR 0531 ...
0531 981 01 90 FULYA KİTAP ALANLAR-PLAK-KİTAP-ANTİKA EŞYA SATIN ALANLAR 0531 ...
 
issue176
issue176issue176
issue176
 
Untitled presentation
Untitled presentationUntitled presentation
Untitled presentation
 
Jka Resume
Jka ResumeJka Resume
Jka Resume
 
0531 981 01 90 YALI KİTAP ALANLAR-PLAK-KİTAP-ANTİKA EŞYA SATIN ALANLAR 0531 9...
0531 981 01 90 YALI KİTAP ALANLAR-PLAK-KİTAP-ANTİKA EŞYA SATIN ALANLAR 0531 9...0531 981 01 90 YALI KİTAP ALANLAR-PLAK-KİTAP-ANTİKA EŞYA SATIN ALANLAR 0531 9...
0531 981 01 90 YALI KİTAP ALANLAR-PLAK-KİTAP-ANTİKA EŞYA SATIN ALANLAR 0531 9...
 
Pcc newsletter letter size 1-12-2012
Pcc newsletter   letter size 1-12-2012Pcc newsletter   letter size 1-12-2012
Pcc newsletter letter size 1-12-2012
 
Discurso Precade
Discurso PrecadeDiscurso Precade
Discurso Precade
 
Review on Document Recommender Systems Using Hierarchical Clustering Techniques
Review on Document Recommender Systems Using Hierarchical Clustering TechniquesReview on Document Recommender Systems Using Hierarchical Clustering Techniques
Review on Document Recommender Systems Using Hierarchical Clustering Techniques
 
Bar Modeling: Using Models to Help Solve Word Problems
Bar Modeling: Using Models to Help Solve Word ProblemsBar Modeling: Using Models to Help Solve Word Problems
Bar Modeling: Using Models to Help Solve Word Problems
 
コンセプトアイデア 1
コンセプトアイデア 1コンセプトアイデア 1
コンセプトアイデア 1
 

Similar to AngularJS, More Than Directives !

Javascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & AngularJavascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & Angular
Erik Guzman
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in react
BOSC Tech Labs
 
AngularJs-training
AngularJs-trainingAngularJs-training
AngularJs-training
Pratchaya Suputsopon
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
Rebecca Murphey
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with Karma
ExoLeaders.com
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
Ryunosuke SATO
 
Building an End-to-End AngularJS Application
Building an End-to-End AngularJS ApplicationBuilding an End-to-End AngularJS Application
Building an End-to-End AngularJS Application
Dan Wahlin
 
$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS
a_sharif
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
Krzysztof Szafranek
 
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
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
Francois Zaninotto
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
Domenic Denicola
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
Tomasz Bak
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
Alexe Bogdan
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bitsChris Saylor
 
The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...
The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...
The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...
Ben Teese
 
AngularJS Testing Strategies
AngularJS Testing StrategiesAngularJS Testing Strategies
AngularJS Testing Strategies
njpst8
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuery
sergioafp
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control Flow
Henrique Barcelos
 

Similar to AngularJS, More Than Directives ! (20)

Javascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & AngularJavascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & Angular
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in react
 
AngularJs-training
AngularJs-trainingAngularJs-training
AngularJs-training
 
Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2Angular Workshop_Sarajevo2
Angular Workshop_Sarajevo2
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
 
Good karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with KarmaGood karma: UX Patterns and Unit Testing in Angular with Karma
Good karma: UX Patterns and Unit Testing in Angular with Karma
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
 
Building an End-to-End AngularJS Application
Building an End-to-End AngularJS ApplicationBuilding an End-to-End AngularJS Application
Building an End-to-End AngularJS Application
 
$q and Promises in AngularJS
$q and Promises in AngularJS $q and Promises in AngularJS
$q and Promises in AngularJS
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...
The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...
The Return of JavaScript: 3 Open-Source Projects that are driving JavaScript'...
 
AngularJS Testing Strategies
AngularJS Testing StrategiesAngularJS Testing Strategies
AngularJS Testing Strategies
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuery
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control Flow
 

Recently uploaded

Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
Vijay Dialani, PhD
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
Divya Somashekar
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
Pratik Pawar
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
MLILAB
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
seandesed
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 

Recently uploaded (20)

Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
ML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptxML for identifying fraud using open blockchain data.pptx
ML for identifying fraud using open blockchain data.pptx
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
block diagram and signal flow graph representation
block diagram and signal flow graph representationblock diagram and signal flow graph representation
block diagram and signal flow graph representation
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
weather web application report.pdf
weather web application report.pdfweather web application report.pdf
weather web application report.pdf
 
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang,  ICLR 2024, MLILAB, KAIST AI.pdfJ.Yang,  ICLR 2024, MLILAB, KAIST AI.pdf
J.Yang, ICLR 2024, MLILAB, KAIST AI.pdf
 
Architectural Portfolio Sean Lockwood
Architectural Portfolio Sean LockwoodArchitectural Portfolio Sean Lockwood
Architectural Portfolio Sean Lockwood
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 

AngularJS, More Than Directives !

  • 1. AngularJS, More Than Directives! - Gaurav Behere - http://www.gauravbehere.in
  • 2. Topics Covered A. Apply/Digest Phase Cycle. B. Handling Memory. C. Transclusion. D. Promises. E. Watch.
  • 3. Apply/Digest Cycle $digest: $digest processes all the watch-Expressions for the current scope and its children What happens when a watch-Expression is processed? The value of the current watch-Expression is compared with the value of the previous watch-Expression, and if they do not match then it is “dirty” and a listener is fired. This is what we call as “Dirty Checking”. Angular doesn’t directly call $digest(). Instead, it calls $scope.$apply(), which in turn calls $rootScope.$digest(). As a result of this, a digest cycle starts at the $rootScope, and subsequently visits all the child scopes calling the watchers along the way.
  • 4. Now, let’s assume you attach an ng-click directive to a button and pass a function name to it. When the button is clicked, AngularJS wraps the function call within $scope.$apply(). So, your function executes as usual, change models (if any), and a $digest cycle starts to ensure your changes are reflected in the view. When & why should I call apply() manually ? When an external event (such as a user action, timer or XHR) is received, the associated expression must be applied to the scope through the $apply() method so that all listeners are updated correctly. It will account for only those model changes which are done inside AngularJS’ context (i.e. the code that changes models is wrapped inside $apply()). Angular’s built-in directives already do this so that any model changes you make are reflected in the view. However, if you change any model outside of the Angular context, then you need to inform Angular of the changes by calling $apply() manually. It’s like telling Angular that you are changing some models and it should fire the watchers so that your changes propagate properly. For example, if you use JavaScript’s setTimeout() function to update a scope model, Angular has no way of knowing what you might change. In this case it’s your responsibility to call $apply() manually, which triggers a $digest cycle. Similarly, if you have a directive that sets up a DOM event listener and changes some models inside the handler function, you need to call $apply() to ensure the changes take effect
  • 5. Example If you use JavaScript’s setTimeout() function to update a scope model, Angular has no way of knowing what you might change. In this case it’s your responsibility to call $apply() manually, which triggers a $digest cycle. HTML <body ng-app="myApp"> <div ng-controller="MessageController"> Delayed Message: {{message}} </div> </body> JS /*Without Apply*/ angular.module('myApp',[]).controller('MessageController', function($scope) { $scope.getMessage = function() { setTimeout(function() { $scope.message = 'Fetched after 3 seconds'; }, 2000); $scope.getMessage(); } JS /*With Apply*/ angular.module('myApp',[]).controller('MessageController', function($scope) { $scope.getMessage = function() { setTimeout(function() { $scope.$apply(function() { $scope.message = 'Fetched after 3 seconds'; }); }, 2000); } $scope.getMessage(); });
  • 6. Handling Memory $destroy() Removes the current scope (and all of its children) from the parent scope. Removal implies that calls to $digest() will no longer propagate to the current scope and its children. Removal also implies that the current scope is eligible for garbage collection. The $destroy() is usually used by directives such as ngRepeat for managing the unrolling of the loop. Just before a scope is destroyed a $destroy event is broadcasted on this scope. Application code can register a $destroy event handler that will give it chance to perform any necessary clean-up. Scope.$destroy(); Calling $destroy() on a scope causes an event “$destroy” to flow downstream.
  • 7. Why & when should I manually handle memory ? If you are using timers to update scope. In cases where you have event listeners. As an example, the following controller continuously updates a model value in one second intervals, and these updates will continue forever, even after the controller’s view is gone and the scope is removed from its parent. module.controller("TestController", function($scope, $timeout) { var onTimeout = function() { $scope.value += 1; $timeout(onTimeout, 1000); }; $timeout(onTimeout, 1000); $scope.value = 0; }); Listening for the $destroy event is an opportunity to halt the timer module.controller("TestController", function($scope, $timeout) { var onTimeout = function() { $scope.value += 1; timer = $timeout(onTimeout, 1000); }; var timer = $timeout(onTimeout, 1000); $scope.value = 0; $scope.$on("$destroy", function() { if (timer) { $timeout.cancel(timer); } }); });
  • 8. Promises The AngularJS $q service is said to be inspired by Chris Kowal's Q library (github.com/kriskowal/q). The library's goal is to allow users to monitor asynchronous progress by providing a "promise" as a return from a call. In AngularJS, the semantics of using a promise are: var promise = callThatRunsInBackground(); promise.then( function(answer) { // do something }, function(error) { // report something }, function(progress) { // report progress });
  • 9. A number of Angular services return promises: $http, $interval, $timeout, for example. All promise returns are single objects; you're expected to research the service itself to find out what it returns. For example, for $http.get, the promise returns an object with four keys:data, status, headers, and config. Those are the same as the four parameters fed to the success callback if you use those semantics: // this $http.get('/api/v1/movies/avengers') .success(function(data, status, headers, config) { $scope.movieContent = data; }); // is the same as var promise = $http.get('/api/v1/movies/avengers'); promise.then( function(payload) { $scope.movieContent = payload.data; });
  • 10. Deferring Promises, Defining Custom Promises: function asyncGreet(name) { var deferred = $q.defer(); setTimeout(function() { deferred.notify('About to greet ' + name + '.'); if (okToGreet(name)) { deferred.resolve('Hello, ' + name + '!'); } else { deferred.reject('Greeting ' + name + ' is not allowed.'); } }, 1000); return deferred.promise; } var promise = asyncGreet('Robin Hood'); promise.then(function(greeting) { alert('Success: ' + greeting); }, function(reason) { alert('Failed: ' + reason); }, function(update) { alert('Got notification: ' + update); });
  • 11. Chaining Promises defer.promise .then(function () { alert("I promised I would show up"); }) .then(function () { alert("me too"); }) .then(function () { alert("and I"); }); defer.resolve(); It is also possible to resolve with parameters. The chained promises will cascade their return values to the subsequent promise: defer.promise .then(function (weapon) { alert("You can have my " + weapon); return "bow"; }) .then(function (weapon) { alert("And my " + weapon); return "axe"; }) .then(function () { alert("And my " + weapon); }); defer.resolve("sword");
  • 12. Transclusion Transclusion provides a way for a consumer of a directive to define a template that is imported into the directive and displayed. For example you might have a directive that outputs a table while allowing the consumer of the directive to control how the table rows are rendered. Or, you might have a directive that outputs an error message while allowing the consumer of the directive to supply HTML content that handles rendering the error using different colors. By supporting this type of functionality the consumer of the directive has more control over how specific parts of the HTML generated by the directive are rendered. Two key features are provided by AngularJS to support transclusion. The first is a property that is used in directives named transclude. When a directive supports transclusion this property is set to true. The second is a directive named ng-transclude that is used to define where external content will be placed in a directive’s template
  • 13. Markup <div ng-app="phoneApp"> <div ng-controller="AppCtrl"> <panel> <div class="button">Click me!</div> </panel> </div> </div> var app = angular.module('phoneApp', []); app.controller("AppCtrl", function ($scope) { }); app.directive("panel", function () { return { restrict: "E", template: '<div class="panel">This is a panel component</div>' } }); return { restruct: "E", transclude: true, template: '<div class="panel" ng-transclude>This is a panel component </div>' }
  • 14. Watch The $scope.watch() function creates a watch of some variable. When you register a watch you pass two functions as parameters to the $watch() function: A value function A listener function Here is an example: $scope.$watch(function() {}, function() {} ); The first function is the value function and the second function is the listener function. The value function should return the value which is being watched. AngularJS can then check the value returned against the value the watch function returned the last time. That way AngularJS can determine if the value has changed. Here is an example: $scope.$watch(function(scope) { return scope.data.myVar }, function() {} ); This example value function returns the $scope variable scope.data.myVar. If the value of this variable changes, a different value will be returned, and AngularJS will call the listener function.
  • 15. The watchExpression is called on every call to $digest() and should return the value that will be watched. (Since $digest() reruns when it detects changes the watchExpression can execute multiple times per $digest() and should be idempotent.) The listener is called only when the value from the current watchExpression and the previous call to watchExpression are not equal (with the exception of the initial run, see below). Inequality is determined according to reference inequality, strict comparison via the !== Javascript operator, unless objectEquality == true (see next point) When objectEquality == true, inequality of the watchExpression is determined according to the angular.equals function. To save the value of the object for later comparison, the angular.copy function is used. This therefore means that watching complex objects will have adverse memory and performance implications. The watch listener may change the model, which may trigger other listeners to fire. This is achieved by rerunning the watchers until no changes are detected. The rerun iteration limit is 10 to prevent an infinite loop deadlock.