SlideShare una empresa de Scribd logo
1 de 24
AngularJS
SCOPE DEMYSTIFIED
Request flow in AngularJS
Module
Routes
Config
ControllerView
Directives
$scope
Factory
Service
Provider
Value
Scope
 is an object that refers to the application model
 Can have properties, functions attached to it
 In case of AngularJS, it gets injected without a need to construct
 Only one root scope, for every angular application
 ng-app – creates the root scope of application
 However can have multiple scopes/child scopes
 Other directives, controllers in app creates these child scopes
Scope - Hierarchy
Scope - Hierarchy
 When executed, the expression {{}} looks for the immediate scope available
 If in case the definition is not available, traces to the parent scope until reaches to
the root scope
 This is prototypical inheritance behaviour in JavaScript
Scope – Life cycle
Scope
Creation
Watcher
Registration
Model
Mutation
Mutation
Observation
Scope
Destruction
The root scope is created during the application bootstrap by the $injector. During
template linking, some directives create new child scopes.
During template linking directives register watches on the scope. These watches will
be used to propagate model values to the DOM.
For mutations to be properly observed, you should make them only within the
scope.$apply(). Angular APIs do this implicitly, so no extra $apply call is needed when
doing synchronous work in controllers, or asynchronous work with $http, $timeout
or $interval services.
At the end of $apply, Angular performs a $digest cycle on the root scope, which then
propagates throughout all child scopes. During the $digest cycle, all $watched
expressions or functions are checked for model mutation and if a mutation is
detected, the $watch listener is called.
When child scopes are no longer needed, it is the responsibility of the child scope
creator to destroy them via scope.$destroy() API.
Scope – DOM
 Scopes are attached to DOM. $scope is the data property that should be looked
after
 To examine the scope in the debugger:
 Right click on the element of interest in your browser and select 'inspect element'. You
should see the browser debugger with the element you clicked on highlighted.
 The debugger allows you to access the currently selected element in the console as $0
variable.
 To retrieve the associated scope in console execute: angular.element($0).scope() or just
type $scope
Scope - Examine
Scope - watchers
 Dirty checking the scope for property changes is a common operation in Angular.
 For this reason the dirty checking function must be efficient.
 Care should be taken that the dirty checking function does not do any DOM access, as
DOM access is orders of magnitude slower than property access on JavaScript object.
 Dirty checking can be done with three strategies: By reference, by collection contents,
and by value.
 The strategies differ in the kinds of changes they detect, and in their performance
characteristics.
Scope – Watchers count
Scope - $watch
 Watching by reference (scope.$watch (watchExpression, listener))
 detects a change when the whole value returned by the watch expression switches
to a new value.
 If the value is an array or an object, changes inside it are not detected. This is the
most efficient strategy.
Scope - $watch
 Expression that is evaluated on each $digest cycle. A change in the return value triggers a call to the
listener.
 string: Evaluated as expression
 function(scope): called with current scope as a parameter.
 Callback called whenever the value of watchExpression changes.
 newVal contains the current value of the watchExpression
 oldVal contains the previous value of the watchExpression
 scope refers to the current scope
 Compare for object equality using angular.equals instead of comparing for reference equality. (default:
false)
Scope - $watch
 Registers a listener callback to be executed whenever the watchExpression changes.
 The watchExpression is called on every call to $digest() and should return the value that will be watched. (watchExpression
should not change its value when executed multiple times with the same input because it may be executed multiple times by
$digest(). That is, watchExpression 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)
 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.
 If you want to be notified whenever $digest is called, you can register a watchExpression function with no listener. (Be prepared
for multiple calls to your watchExpression because it will execute multiple times in a single $digest cycle if a change is
detected.)
 After a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync) to initialize the watcher. In
rare cases, this is undesirable because the listener is called when the result of watchExpression didn't change. To detect this
scenario within the listener fn, you can compare the newVal and oldVal. If these two values are identical (===) then the listener
was called due to initialization.
Scope - $watchCollection
 Watching collection contents (scope.$watchCollection (watchExpression, listener))
detects changes that occur inside an array or an object: When items are added,
removed, or reordered.
 The detection is shallow - it does not reach into nested collections.
 Watching collection contents is more expensive than watching by reference,
because copies of the collection contents need to be maintained.
 However, the strategy attempts to minimize the amount of copying required.
Scope - $watch value
 Watching by value (scope.$watch (watchExpression, listener, true))
 detects any change in an arbitrarily nested data structure.
 It is the most powerful change detection strategy, but also the most expensive.
 A full traversal of the nested data structure is needed on each digest, and a full
copy of it needs to be held in memory.
Scope - $apply
 $apply() is used to execute an expression in angular from outside of the angular framework.
 For example from browser DOM events, setTimeout, XHR or third party libraries.
 Because we are calling into the angular framework we need to perform proper scope life cycle of
exception handling, executing watches.
 An AngularJS $scope has a function called $apply() which takes a function as an argument.
 So, you simply need to put the code that changes models inside a function and call $scope.$apply()
passing that function as an argument.
 After the $apply() function call ends, AngularJS knows that some model changes might have occurred. It
then starts a digest cycle by calling another function $rootScope.$digest()―which propagates to all child
scopes.
Scope - $digest
 After the $apply() function call ends, AngularJS knows that some model changes might have occurred. It
then starts a digest cycle by calling another function $rootScope.$digest()―which propagates to all child
scopes.
 In the digest cycle all the watchers are called to check if the model value has changed.
 After calling the listener functions, the digest cycle starts all over again and fires each watcher to check if
any of the models have been mutated in the last loop.
 The digest cycle continues to loop until no model changes have been detected or it hits the maximum
loop count of 10 (whichever comes first).
 At a minimum the $digest() cycle runs twice even if there are no model mutation in the listener functions.
Scope - $digest
 The cycle runs once more to make sure the models are stable and no change has been made in last loop.
This is called dirty checking.
 If you want to get notified whenever $digest() is called, you can set up a watcher without any listener
function.
 The first and only argument to $scope.$watch() should be the function whose return value you want to
monitor.
 This function gets called in every digest cycle.
 That is why the second argument to $watch() is optional.
 Calling $apply() will automatically trigger a $digest on $rootScope which subsequently visits all the child
scopes calling the watchers.
Scope – Events propagation
 Scopes can propagate events in similar
fashion to DOM events. The event can be
broadcasted to the scope children or
emitted to scope parents.
Scope – Broadcast, Emit
 $scope.$broadcast(name,args) For Broadcasting Events
 The $broadcast() function is the same as $emit() except the event propagates
downwards in the scope hierarchy to all the child scopes.
 The parameters list is also same as that of $emit().
 Like $emit, the $scope which broadcasts the event also receives a notification
(via $on) when it's broadcast.
Scope - on
 $scope.$on(name,handlerFunction) For Registering Listeners
 The $on function registers event listeners that should be called when the event
occurs.
 The first parameter is the name of the event you are interested in.
 The second parameter is a callback function which gets called when the event
occurs.
Scope – Broadcast, Emit, On
Scope - destroy
 When a scope is being destroyed a $destroy event is broadcast on the scope.
 You can listen for this event and perform any necessary cleanups.
References
 https://docs.angularjs.org/guide/scope

Más contenido relacionado

La actualidad más candente

Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptDhruvin Shah
 
Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Jalpesh Vasa
 
Javascript - Tutorial
Javascript - TutorialJavascript - Tutorial
Javascript - Tutorialadelaticleanu
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
Introduction to JavaScript Programming
Introduction to JavaScript ProgrammingIntroduction to JavaScript Programming
Introduction to JavaScript ProgrammingRaveendra R
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptWalid Ashraf
 
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...Knoldus Inc.
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript ProgrammingSehwan Noh
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features OverviewSergii Stets
 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhHarmeet Singh(Taara)
 
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Harmeet Singh(Taara)
 
Objects and classes in Visual Basic
Objects and classes in Visual BasicObjects and classes in Visual Basic
Objects and classes in Visual BasicSangeetha Sg
 
Qtp training session IV
Qtp training session IVQtp training session IV
Qtp training session IVAisha Mazhar
 

La actualidad más candente (20)

Of Lambdas and LINQ
Of Lambdas and LINQOf Lambdas and LINQ
Of Lambdas and LINQ
 
Mule java part-4
Mule java part-4Mule java part-4
Mule java part-4
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1
 
Javascript - Tutorial
Javascript - TutorialJavascript - Tutorial
Javascript - Tutorial
 
Spring boot
Spring bootSpring boot
Spring boot
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
C#/.NET Little Pitfalls
C#/.NET Little PitfallsC#/.NET Little Pitfalls
C#/.NET Little Pitfalls
 
JS - Basics
JS - BasicsJS - Basics
JS - Basics
 
Introduction to JavaScript Programming
Introduction to JavaScript ProgrammingIntroduction to JavaScript Programming
Introduction to JavaScript Programming
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
 
Java script function
Java script functionJava script function
Java script function
 
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
Play framework training by Neelkanth Sachdeva @ Scala traits event , New Delh...
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
Functional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singhFunctional programming in java 8 by harmeet singh
Functional programming in java 8 by harmeet singh
 
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
 
Objects and classes in Visual Basic
Objects and classes in Visual BasicObjects and classes in Visual Basic
Objects and classes in Visual Basic
 
Qtp training session IV
Qtp training session IVQtp training session IV
Qtp training session IV
 

Destacado

Angularjs cascade
Angularjs cascadeAngularjs cascade
Angularjs cascadehannonhill
 
Angular 1.5 Components
Angular 1.5 ComponentsAngular 1.5 Components
Angular 1.5 ComponentsJosé Barbosa
 
gDayX 2013 - Advanced AngularJS - Nicolas Embleton
gDayX 2013 - Advanced AngularJS - Nicolas EmbletongDayX 2013 - Advanced AngularJS - Nicolas Embleton
gDayX 2013 - Advanced AngularJS - Nicolas EmbletonGeorge Nguyen
 
U7 ha thao software development
U7 ha thao software developmentU7 ha thao software development
U7 ha thao software developmentandynova
 
FrontEnd platform based on AngularJS
FrontEnd platform based on AngularJSFrontEnd platform based on AngularJS
FrontEnd platform based on AngularJSEgor Miasnikov
 
Building Modern Web Apps with AngularJS
Building Modern Web Apps with AngularJSBuilding Modern Web Apps with AngularJS
Building Modern Web Apps with AngularJSRaveen Perera
 
AngularJS Beginners Workshop
AngularJS Beginners WorkshopAngularJS Beginners Workshop
AngularJS Beginners WorkshopSathish VJ
 
Creating GUI Component APIs in Angular and Web Components
Creating GUI Component APIs in Angular and Web ComponentsCreating GUI Component APIs in Angular and Web Components
Creating GUI Component APIs in Angular and Web ComponentsRachael L Moore
 
29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview Questions29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview QuestionsArc & Codementor
 
Advanced AngularJS Concepts
Advanced AngularJS ConceptsAdvanced AngularJS Concepts
Advanced AngularJS ConceptsKyle Hodgson
 

Destacado (14)

Angularjs cascade
Angularjs cascadeAngularjs cascade
Angularjs cascade
 
Angular 1.5 Components
Angular 1.5 ComponentsAngular 1.5 Components
Angular 1.5 Components
 
gDayX 2013 - Advanced AngularJS - Nicolas Embleton
gDayX 2013 - Advanced AngularJS - Nicolas EmbletongDayX 2013 - Advanced AngularJS - Nicolas Embleton
gDayX 2013 - Advanced AngularJS - Nicolas Embleton
 
U7 ha thao software development
U7 ha thao software developmentU7 ha thao software development
U7 ha thao software development
 
FrontEnd platform based on AngularJS
FrontEnd platform based on AngularJSFrontEnd platform based on AngularJS
FrontEnd platform based on AngularJS
 
Dependency injection
Dependency injectionDependency injection
Dependency injection
 
Building Modern Web Apps with AngularJS
Building Modern Web Apps with AngularJSBuilding Modern Web Apps with AngularJS
Building Modern Web Apps with AngularJS
 
AngularJS Beginners Workshop
AngularJS Beginners WorkshopAngularJS Beginners Workshop
AngularJS Beginners Workshop
 
AngularJS Testing
AngularJS TestingAngularJS Testing
AngularJS Testing
 
Creating GUI Component APIs in Angular and Web Components
Creating GUI Component APIs in Angular and Web ComponentsCreating GUI Component APIs in Angular and Web Components
Creating GUI Component APIs in Angular and Web Components
 
Introduction to AngularJs
Introduction to AngularJsIntroduction to AngularJs
Introduction to AngularJs
 
29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview Questions29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview Questions
 
Nicolas Embleton, Advanced Angular JS
Nicolas Embleton, Advanced Angular JSNicolas Embleton, Advanced Angular JS
Nicolas Embleton, Advanced Angular JS
 
Advanced AngularJS Concepts
Advanced AngularJS ConceptsAdvanced AngularJS Concepts
Advanced AngularJS Concepts
 

Similar a Scope demystified - AngularJS

Dive into Angular, part 3: Performance
Dive into Angular, part 3: PerformanceDive into Angular, part 3: Performance
Dive into Angular, part 3: PerformanceOleksii Prohonnyi
 
Data binding in AngularJS, from model to view
Data binding in AngularJS, from model to viewData binding in AngularJS, from model to view
Data binding in AngularJS, from model to viewThomas Roch
 
AngularJs presentation
AngularJs presentation AngularJs presentation
AngularJs presentation Phan Tuan
 
Knockoutjs Part 2 Beginners
Knockoutjs Part 2 BeginnersKnockoutjs Part 2 Beginners
Knockoutjs Part 2 BeginnersBhaumik Patel
 
Scope.js prsentation
Scope.js prsentationScope.js prsentation
Scope.js prsentationAtishay Baid
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !Gaurav Behere
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 SlidesYarikS
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdfvenud11
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async LibraryKnoldus Inc.
 
Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2JollyRogers5
 
AngularJS Tips&Tricks
AngularJS Tips&TricksAngularJS Tips&Tricks
AngularJS Tips&TricksPetr Bela
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptFu Cheng
 
Scope in AngularJs
Scope in AngularJsScope in AngularJs
Scope in AngularJsThien To
 
Containers & Dependency in Ember.js
Containers & Dependency in Ember.jsContainers & Dependency in Ember.js
Containers & Dependency in Ember.jsMatthew Beale
 
Postman API testing with pre & post scripting
Postman API testing with pre & post scriptingPostman API testing with pre & post scripting
Postman API testing with pre & post scriptingITlearn360
 

Similar a Scope demystified - AngularJS (20)

Dive into Angular, part 3: Performance
Dive into Angular, part 3: PerformanceDive into Angular, part 3: Performance
Dive into Angular, part 3: Performance
 
AngularJS Scopes
AngularJS ScopesAngularJS Scopes
AngularJS Scopes
 
Data binding in AngularJS, from model to view
Data binding in AngularJS, from model to viewData binding in AngularJS, from model to view
Data binding in AngularJS, from model to view
 
AngularJs presentation
AngularJs presentation AngularJs presentation
AngularJs presentation
 
Knockoutjs Part 2 Beginners
Knockoutjs Part 2 BeginnersKnockoutjs Part 2 Beginners
Knockoutjs Part 2 Beginners
 
Angularjs Performance
Angularjs PerformanceAngularjs Performance
Angularjs Performance
 
Scope.js prsentation
Scope.js prsentationScope.js prsentation
Scope.js prsentation
 
AngularJS, More Than Directives !
AngularJS, More Than Directives !AngularJS, More Than Directives !
AngularJS, More Than Directives !
 
RxJava2 Slides
RxJava2 SlidesRxJava2 Slides
RxJava2 Slides
 
1669958779195.pdf
1669958779195.pdf1669958779195.pdf
1669958779195.pdf
 
AngularJs Crash Course
AngularJs Crash CourseAngularJs Crash Course
AngularJs Crash Course
 
Controller
ControllerController
Controller
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async Library
 
Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2Intro to Reactive Thinking and RxJava 2
Intro to Reactive Thinking and RxJava 2
 
AngularJS Tips&Tricks
AngularJS Tips&TricksAngularJS Tips&Tricks
AngularJS Tips&Tricks
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Scope in AngularJs
Scope in AngularJsScope in AngularJs
Scope in AngularJs
 
Containers & Dependency in Ember.js
Containers & Dependency in Ember.jsContainers & Dependency in Ember.js
Containers & Dependency in Ember.js
 
G pars
G parsG pars
G pars
 
Postman API testing with pre & post scripting
Postman API testing with pre & post scriptingPostman API testing with pre & post scripting
Postman API testing with pre & post scripting
 

Más de Sumanth krishna

Jasmine - A BDD test framework for JavaScript
Jasmine - A BDD test framework for JavaScriptJasmine - A BDD test framework for JavaScript
Jasmine - A BDD test framework for JavaScriptSumanth krishna
 
Ruby on Rails industry trends
Ruby on Rails industry trendsRuby on Rails industry trends
Ruby on Rails industry trendsSumanth krishna
 
Introducing Ruby/MVC/RoR
Introducing Ruby/MVC/RoRIntroducing Ruby/MVC/RoR
Introducing Ruby/MVC/RoRSumanth krishna
 
Watir Presentation Sumanth Krishna. A
Watir Presentation   Sumanth Krishna. AWatir Presentation   Sumanth Krishna. A
Watir Presentation Sumanth Krishna. ASumanth krishna
 
Ro R Based Social Networking Apps Compared
Ro R Based Social Networking Apps ComparedRo R Based Social Networking Apps Compared
Ro R Based Social Networking Apps ComparedSumanth krishna
 
New Rabbit Tortoise Story
New Rabbit   Tortoise StoryNew Rabbit   Tortoise Story
New Rabbit Tortoise StorySumanth krishna
 
RoR relevance to startups Session @ Barcamp5 - Sumanth Krishna
RoR relevance to startups Session @ Barcamp5 - Sumanth KrishnaRoR relevance to startups Session @ Barcamp5 - Sumanth Krishna
RoR relevance to startups Session @ Barcamp5 - Sumanth KrishnaSumanth krishna
 
How Brain Works against in identifying colors?
How Brain Works against in identifying colors?How Brain Works against in identifying colors?
How Brain Works against in identifying colors?Sumanth krishna
 

Más de Sumanth krishna (11)

Jasmine - A BDD test framework for JavaScript
Jasmine - A BDD test framework for JavaScriptJasmine - A BDD test framework for JavaScript
Jasmine - A BDD test framework for JavaScript
 
Ruby on Rails industry trends
Ruby on Rails industry trendsRuby on Rails industry trends
Ruby on Rails industry trends
 
Introducing Ruby/MVC/RoR
Introducing Ruby/MVC/RoRIntroducing Ruby/MVC/RoR
Introducing Ruby/MVC/RoR
 
Watir Presentation Sumanth Krishna. A
Watir Presentation   Sumanth Krishna. AWatir Presentation   Sumanth Krishna. A
Watir Presentation Sumanth Krishna. A
 
Life Pencil And U
Life Pencil And ULife Pencil And U
Life Pencil And U
 
Ro R Based Social Networking Apps Compared
Ro R Based Social Networking Apps ComparedRo R Based Social Networking Apps Compared
Ro R Based Social Networking Apps Compared
 
Put The Glass Down
Put The Glass DownPut The Glass Down
Put The Glass Down
 
New Rabbit Tortoise Story
New Rabbit   Tortoise StoryNew Rabbit   Tortoise Story
New Rabbit Tortoise Story
 
RoR relevance to startups Session @ Barcamp5 - Sumanth Krishna
RoR relevance to startups Session @ Barcamp5 - Sumanth KrishnaRoR relevance to startups Session @ Barcamp5 - Sumanth Krishna
RoR relevance to startups Session @ Barcamp5 - Sumanth Krishna
 
Cookie - story
Cookie - storyCookie - story
Cookie - story
 
How Brain Works against in identifying colors?
How Brain Works against in identifying colors?How Brain Works against in identifying colors?
How Brain Works against in identifying colors?
 

Último

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 

Último (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 

Scope demystified - AngularJS

  • 2. Request flow in AngularJS Module Routes Config ControllerView Directives $scope Factory Service Provider Value
  • 3. Scope  is an object that refers to the application model  Can have properties, functions attached to it  In case of AngularJS, it gets injected without a need to construct  Only one root scope, for every angular application  ng-app – creates the root scope of application  However can have multiple scopes/child scopes  Other directives, controllers in app creates these child scopes
  • 5. Scope - Hierarchy  When executed, the expression {{}} looks for the immediate scope available  If in case the definition is not available, traces to the parent scope until reaches to the root scope  This is prototypical inheritance behaviour in JavaScript
  • 6. Scope – Life cycle Scope Creation Watcher Registration Model Mutation Mutation Observation Scope Destruction The root scope is created during the application bootstrap by the $injector. During template linking, some directives create new child scopes. During template linking directives register watches on the scope. These watches will be used to propagate model values to the DOM. For mutations to be properly observed, you should make them only within the scope.$apply(). Angular APIs do this implicitly, so no extra $apply call is needed when doing synchronous work in controllers, or asynchronous work with $http, $timeout or $interval services. At the end of $apply, Angular performs a $digest cycle on the root scope, which then propagates throughout all child scopes. During the $digest cycle, all $watched expressions or functions are checked for model mutation and if a mutation is detected, the $watch listener is called. When child scopes are no longer needed, it is the responsibility of the child scope creator to destroy them via scope.$destroy() API.
  • 7. Scope – DOM  Scopes are attached to DOM. $scope is the data property that should be looked after  To examine the scope in the debugger:  Right click on the element of interest in your browser and select 'inspect element'. You should see the browser debugger with the element you clicked on highlighted.  The debugger allows you to access the currently selected element in the console as $0 variable.  To retrieve the associated scope in console execute: angular.element($0).scope() or just type $scope
  • 9. Scope - watchers  Dirty checking the scope for property changes is a common operation in Angular.  For this reason the dirty checking function must be efficient.  Care should be taken that the dirty checking function does not do any DOM access, as DOM access is orders of magnitude slower than property access on JavaScript object.  Dirty checking can be done with three strategies: By reference, by collection contents, and by value.  The strategies differ in the kinds of changes they detect, and in their performance characteristics.
  • 11. Scope - $watch  Watching by reference (scope.$watch (watchExpression, listener))  detects a change when the whole value returned by the watch expression switches to a new value.  If the value is an array or an object, changes inside it are not detected. This is the most efficient strategy.
  • 12. Scope - $watch  Expression that is evaluated on each $digest cycle. A change in the return value triggers a call to the listener.  string: Evaluated as expression  function(scope): called with current scope as a parameter.  Callback called whenever the value of watchExpression changes.  newVal contains the current value of the watchExpression  oldVal contains the previous value of the watchExpression  scope refers to the current scope  Compare for object equality using angular.equals instead of comparing for reference equality. (default: false)
  • 13. Scope - $watch  Registers a listener callback to be executed whenever the watchExpression changes.  The watchExpression is called on every call to $digest() and should return the value that will be watched. (watchExpression should not change its value when executed multiple times with the same input because it may be executed multiple times by $digest(). That is, watchExpression 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)  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.  If you want to be notified whenever $digest is called, you can register a watchExpression function with no listener. (Be prepared for multiple calls to your watchExpression because it will execute multiple times in a single $digest cycle if a change is detected.)  After a watcher is registered with the scope, the listener fn is called asynchronously (via $evalAsync) to initialize the watcher. In rare cases, this is undesirable because the listener is called when the result of watchExpression didn't change. To detect this scenario within the listener fn, you can compare the newVal and oldVal. If these two values are identical (===) then the listener was called due to initialization.
  • 14. Scope - $watchCollection  Watching collection contents (scope.$watchCollection (watchExpression, listener)) detects changes that occur inside an array or an object: When items are added, removed, or reordered.  The detection is shallow - it does not reach into nested collections.  Watching collection contents is more expensive than watching by reference, because copies of the collection contents need to be maintained.  However, the strategy attempts to minimize the amount of copying required.
  • 15. Scope - $watch value  Watching by value (scope.$watch (watchExpression, listener, true))  detects any change in an arbitrarily nested data structure.  It is the most powerful change detection strategy, but also the most expensive.  A full traversal of the nested data structure is needed on each digest, and a full copy of it needs to be held in memory.
  • 16. Scope - $apply  $apply() is used to execute an expression in angular from outside of the angular framework.  For example from browser DOM events, setTimeout, XHR or third party libraries.  Because we are calling into the angular framework we need to perform proper scope life cycle of exception handling, executing watches.  An AngularJS $scope has a function called $apply() which takes a function as an argument.  So, you simply need to put the code that changes models inside a function and call $scope.$apply() passing that function as an argument.  After the $apply() function call ends, AngularJS knows that some model changes might have occurred. It then starts a digest cycle by calling another function $rootScope.$digest()―which propagates to all child scopes.
  • 17. Scope - $digest  After the $apply() function call ends, AngularJS knows that some model changes might have occurred. It then starts a digest cycle by calling another function $rootScope.$digest()―which propagates to all child scopes.  In the digest cycle all the watchers are called to check if the model value has changed.  After calling the listener functions, the digest cycle starts all over again and fires each watcher to check if any of the models have been mutated in the last loop.  The digest cycle continues to loop until no model changes have been detected or it hits the maximum loop count of 10 (whichever comes first).  At a minimum the $digest() cycle runs twice even if there are no model mutation in the listener functions.
  • 18. Scope - $digest  The cycle runs once more to make sure the models are stable and no change has been made in last loop. This is called dirty checking.  If you want to get notified whenever $digest() is called, you can set up a watcher without any listener function.  The first and only argument to $scope.$watch() should be the function whose return value you want to monitor.  This function gets called in every digest cycle.  That is why the second argument to $watch() is optional.  Calling $apply() will automatically trigger a $digest on $rootScope which subsequently visits all the child scopes calling the watchers.
  • 19. Scope – Events propagation  Scopes can propagate events in similar fashion to DOM events. The event can be broadcasted to the scope children or emitted to scope parents.
  • 20. Scope – Broadcast, Emit  $scope.$broadcast(name,args) For Broadcasting Events  The $broadcast() function is the same as $emit() except the event propagates downwards in the scope hierarchy to all the child scopes.  The parameters list is also same as that of $emit().  Like $emit, the $scope which broadcasts the event also receives a notification (via $on) when it's broadcast.
  • 21. Scope - on  $scope.$on(name,handlerFunction) For Registering Listeners  The $on function registers event listeners that should be called when the event occurs.  The first parameter is the name of the event you are interested in.  The second parameter is a callback function which gets called when the event occurs.
  • 23. Scope - destroy  When a scope is being destroyed a $destroy event is broadcast on the scope.  You can listen for this event and perform any necessary cleanups.