SlideShare a Scribd company logo
Scope in AngularJS
To Duc Thien - June 23, 2016
Contents
• Overview
• JavaScript prototypal inheritance
• Angular scope inheritance
• Q&A
Overview: Scopes
What's scopes?
• The source of truth for application state
• Execution context for expression
• Map mimics DOM structure
• Agency to watch expression and propagate events
Overview: Scopes
Scopes' main features:
• Observe model mutations ($watch)
• Propagate model changes to whole application ($apply)
• Can be nested to limit access from other components
• Provide execution environment to evaluate expressions
E.g: {{2 + 3}}
Overview: Scope
$rootScope and $scope
• $rootScope: global context in Angular apps
Parents of all $scope object, initialize with Angular application
<div ng-app="App"></div>
• $scope: peculiar data model object
Connection between controller and view
angular.module('App', []).controller('AppController', function($scope) {...});
angular.module('App', []).directive('myDirective', function(){
return {
controller: function($scope) { ... },
link: function(scope, element, attr) { ... }
}
});
Overview: Scope
Scope life cycle
• Creation
• Watcher registration
• Model mutation
• Mutation observation
• Destruction
Javascript prototypal inheritance
function Human(name) {
this.name = name;
}
Human.prototype.say = function() {
console.log('I am an' + this.name);
}
var myDad = new Human('Billionaire');
myDad.money = 1000000;
myDad.cars = ['BMW X6', 'RR Phantom', 'Maybach'];
myDad.houses = {hanoi: 200, saigon: 500};
var me = Object.create(myDad);
me.money = -50000;
me.cars[1] = "Honda Super Dream";
me.houses.hanoi = 100;
Human
myDad
Cars: ['BMW X6', 'RR Phantom','Maybach']
Money: 1000000
houses: {hanoi: 200, saigon: 500}
me Money: -50000
Javascript prototypal inheritance
• To find a property in child object
• Searching in child object
• Not found -> looking in inherited object
• New properties of child object will hide/shadows parent property with the same
name
• If objects are found in parent, the property will be updated on original object
Angular scope inheritance
Normal prototypal scope inheritance in AngularJS
• Ng-controller
• Ng-include
• Ng-switch
• Directive with scope: true
Angular scope inheritance
Ng-repeat
• Normal prototypal inheritance with copy/assignment
• Each iteration create new child scope
• Child scopes get new properties
childScope = scope.$new(); // child scope prototypically inherits from parent scope ...
childScope[valueIdent] = value; // creates a new childScope property
Angular scope inheritance
Directive - isolated scope (scope: {...})
• Not prototypal inheritance
• Various option to access parent scopes through attributes:
• '=': two-way data binding
• '@': one-way data binding
• '&': bind to parent expression
Angular scope inheritance
Directive - transcluded scope (transcluded: true)
• Beside of isolated scope, new transcluded scope is
created
• New transcluded scope is inherited from parent scope
• Avoid child scope hiding/shadowing parent scope's
properties
• Both isolated scope and transcluded scope can
access to parent scope through $parent
References
• https://docs.angularjs.org/guide/scope
• https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-
prototypal-inheritance
• ng-book - The in-depth, complete, and up-to-date book on Angular. Become
an AngularJS expert today.
Thank you

More Related Content

PPTX
Introduction to underscore.js
Jitendra Zaa
 
PDF
Swift after one week of coding
SwiftWro
 
PDF
Realm.io par Clement Sauvage
CocoaHeads France
 
PDF
Angular Data
Stefan Unterhofer
 
PPTX
Angular js
Brian Atkins
 
PDF
クリーンアーキテクチャーを強制する方法を考えてみた(N番煎じ) #すえなみチャンス暑気払い
Shinya Mochida
 
PDF
Property wrapper and how to use them with mvvm in swift ui i copy
WannitaTolaema
 
PDF
Icinga2 api use cases
roy peter
 
Introduction to underscore.js
Jitendra Zaa
 
Swift after one week of coding
SwiftWro
 
Realm.io par Clement Sauvage
CocoaHeads France
 
Angular Data
Stefan Unterhofer
 
Angular js
Brian Atkins
 
クリーンアーキテクチャーを強制する方法を考えてみた(N番煎じ) #すえなみチャンス暑気払い
Shinya Mochida
 
Property wrapper and how to use them with mvvm in swift ui i copy
WannitaTolaema
 
Icinga2 api use cases
roy peter
 

What's hot (6)

KEY
Core animation
Weizhong Yang
 
PPTX
Introduction to RxJS
Abul Hasan
 
PPTX
Mobile TechTalk - Interesting talks from NSConference 6
GlobalLogic Ukraine
 
PDF
Lightweight wrapper for Hive on Amazon EMR
Shinji Tanaka
 
PDF
DOM Performance (JSNext Bulgaria)
Hristo Chakarov
 
PPTX
ES6 Primer
roblund
 
Core animation
Weizhong Yang
 
Introduction to RxJS
Abul Hasan
 
Mobile TechTalk - Interesting talks from NSConference 6
GlobalLogic Ukraine
 
Lightweight wrapper for Hive on Amazon EMR
Shinji Tanaka
 
DOM Performance (JSNext Bulgaria)
Hristo Chakarov
 
ES6 Primer
roblund
 
Ad

Viewers also liked (20)

PPTX
Angular Deep Directive
Henry Tao
 
PPTX
AngularJs presentation
Phan Tuan
 
DOCX
Angular.js interview questions
codeandyou forums
 
PDF
Custom AngularJS Directives
yprodev
 
PPTX
AngularJS custom directive
Nascenia IT
 
PPTX
Step by Step - AngularJS
Infragistics
 
PDF
Building Custom AngularJS Directives - A Step-by-Step Guide - Dan Wahlin | Fa...
FalafelSoftware
 
PPTX
Ghtptynfwbz
Ilusha12345
 
PDF
Paradigm Drilling Equipment
Ian McGillivray
 
PDF
20150506133355
Loyiso Feni
 
PDF
Case Study
Cleverativity
 
PPSX
Apresentação Marcas e Patentes VIX
Eduardo Moraes
 
PDF
WWL_Presentation
Valeria Vardanjan
 
PDF
Præsentation hotel opus horsens 2014 save as
Betina Kömmler
 
PDF
Modern Mobile Friendly Websites
Cleverativity
 
PDF
Louis-Pierre Geerinckx VRACHTFIETS
Louis Pierre Geerinckx
 
PPTX
Land pollution
Mrscato
 
PDF
CV Alief
Alief Castollani
 
PDF
Hotel Opus Horsens
Betina Kömmler
 
PPTX
Kelompok 8 pengemasan
M Rafsanjany
 
Angular Deep Directive
Henry Tao
 
AngularJs presentation
Phan Tuan
 
Angular.js interview questions
codeandyou forums
 
Custom AngularJS Directives
yprodev
 
AngularJS custom directive
Nascenia IT
 
Step by Step - AngularJS
Infragistics
 
Building Custom AngularJS Directives - A Step-by-Step Guide - Dan Wahlin | Fa...
FalafelSoftware
 
Ghtptynfwbz
Ilusha12345
 
Paradigm Drilling Equipment
Ian McGillivray
 
20150506133355
Loyiso Feni
 
Case Study
Cleverativity
 
Apresentação Marcas e Patentes VIX
Eduardo Moraes
 
WWL_Presentation
Valeria Vardanjan
 
Præsentation hotel opus horsens 2014 save as
Betina Kömmler
 
Modern Mobile Friendly Websites
Cleverativity
 
Louis-Pierre Geerinckx VRACHTFIETS
Louis Pierre Geerinckx
 
Land pollution
Mrscato
 
Hotel Opus Horsens
Betina Kömmler
 
Kelompok 8 pengemasan
M Rafsanjany
 
Ad

Similar to Scope in AngularJs (20)

PPTX
AngularJS Scopes
Mohamed Elkhodary
 
PPTX
Angular js
Baldeep Sohal
 
PPTX
AngularJS.part1
Andrey Kolodnitsky
 
PPTX
Angular js
Larry Ball
 
PPTX
Angular js 1.0-fundamentals
Venkatesh Narayanan
 
PPTX
Introduction to AngularJS
David Parsons
 
PPTX
Basics of AngularJS
Filip Janevski
 
KEY
Django class based views (Dutch Django meeting presentation)
Reinout van Rees
 
PDF
Angular or Backbone: Go Mobile!
Doris Chen
 
ODP
AngularJs Crash Course
Keith Bloomfield
 
PPTX
AngularJS Best Practices
Narek Mamikonyan
 
PPTX
JavaScripters Event Oct 22, 2016 · 2:00 PM: Common Mistakes made by Angular D...
JavaScripters Community
 
DOCX
Understanding angular js $rootscope and $scope
Brajesh Yadav
 
PPT
Coffee@DBG - Exploring Angular JS
Deepu S Nath
 
PPT
angularjsmeetup-150303044616-conversion-gate01
Teo E
 
PPT
Angular js meetup
Pierre-Yves Gicquel
 
PPTX
Angular
LearningTech
 
PPTX
Angular
LearningTech
 
PPTX
Quick Start to AngularJS
Return on Intelligence
 
PPTX
Building AngularJS Custom Directives
Dan Wahlin
 
AngularJS Scopes
Mohamed Elkhodary
 
Angular js
Baldeep Sohal
 
AngularJS.part1
Andrey Kolodnitsky
 
Angular js
Larry Ball
 
Angular js 1.0-fundamentals
Venkatesh Narayanan
 
Introduction to AngularJS
David Parsons
 
Basics of AngularJS
Filip Janevski
 
Django class based views (Dutch Django meeting presentation)
Reinout van Rees
 
Angular or Backbone: Go Mobile!
Doris Chen
 
AngularJs Crash Course
Keith Bloomfield
 
AngularJS Best Practices
Narek Mamikonyan
 
JavaScripters Event Oct 22, 2016 · 2:00 PM: Common Mistakes made by Angular D...
JavaScripters Community
 
Understanding angular js $rootscope and $scope
Brajesh Yadav
 
Coffee@DBG - Exploring Angular JS
Deepu S Nath
 
angularjsmeetup-150303044616-conversion-gate01
Teo E
 
Angular js meetup
Pierre-Yves Gicquel
 
Angular
LearningTech
 
Angular
LearningTech
 
Quick Start to AngularJS
Return on Intelligence
 
Building AngularJS Custom Directives
Dan Wahlin
 

Recently uploaded (20)

PDF
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
Hironori Washizaki
 
PDF
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
PDF
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
PPTX
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
PDF
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
PDF
Become an Agentblazer Champion Challenge Kickoff
Dele Amefo
 
PDF
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 
PPTX
TestNG for Java Testing and Automation testing
ssuser0213cb
 
PDF
Bandai Playdia The Book - David Glotz
BluePanther6
 
PDF
Exploring AI Agents in Process Industries
amoreira6
 
PDF
Protecting the Digital World Cyber Securit
dnthakkar16
 
DOCX
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
PPTX
Can You Build Dashboards Using Open Source Visualization Tool.pptx
Varsha Nayak
 
PDF
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
PPTX
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
PPTX
Why Use Open Source Reporting Tools for Business Intelligence.pptx
Varsha Nayak
 
PPTX
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pptx
Certivo Inc
 
PPTX
Presentation about variables and constant.pptx
kr2589474
 
PPTX
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
IEEE-CS Tech Predictions, SWEBOK and Quantum Software: Towards Q-SWEBOK
Hironori Washizaki
 
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
Explanation about Structures in C language.pptx
Veeral Rathod
 
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
Become an Agentblazer Champion Challenge Kickoff
Dele Amefo
 
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 
TestNG for Java Testing and Automation testing
ssuser0213cb
 
Bandai Playdia The Book - David Glotz
BluePanther6
 
Exploring AI Agents in Process Industries
amoreira6
 
Protecting the Digital World Cyber Securit
dnthakkar16
 
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
Can You Build Dashboards Using Open Source Visualization Tool.pptx
Varsha Nayak
 
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
Why Use Open Source Reporting Tools for Business Intelligence.pptx
Varsha Nayak
 
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pptx
Certivo Inc
 
Presentation about variables and constant.pptx
kr2589474
 
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 

Scope in AngularJs

  • 1. Scope in AngularJS To Duc Thien - June 23, 2016
  • 2. Contents • Overview • JavaScript prototypal inheritance • Angular scope inheritance • Q&A
  • 3. Overview: Scopes What's scopes? • The source of truth for application state • Execution context for expression • Map mimics DOM structure • Agency to watch expression and propagate events
  • 4. Overview: Scopes Scopes' main features: • Observe model mutations ($watch) • Propagate model changes to whole application ($apply) • Can be nested to limit access from other components • Provide execution environment to evaluate expressions E.g: {{2 + 3}}
  • 5. Overview: Scope $rootScope and $scope • $rootScope: global context in Angular apps Parents of all $scope object, initialize with Angular application <div ng-app="App"></div> • $scope: peculiar data model object Connection between controller and view angular.module('App', []).controller('AppController', function($scope) {...}); angular.module('App', []).directive('myDirective', function(){ return { controller: function($scope) { ... }, link: function(scope, element, attr) { ... } } });
  • 6. Overview: Scope Scope life cycle • Creation • Watcher registration • Model mutation • Mutation observation • Destruction
  • 7. Javascript prototypal inheritance function Human(name) { this.name = name; } Human.prototype.say = function() { console.log('I am an' + this.name); } var myDad = new Human('Billionaire'); myDad.money = 1000000; myDad.cars = ['BMW X6', 'RR Phantom', 'Maybach']; myDad.houses = {hanoi: 200, saigon: 500}; var me = Object.create(myDad); me.money = -50000; me.cars[1] = "Honda Super Dream"; me.houses.hanoi = 100; Human myDad Cars: ['BMW X6', 'RR Phantom','Maybach'] Money: 1000000 houses: {hanoi: 200, saigon: 500} me Money: -50000
  • 8. Javascript prototypal inheritance • To find a property in child object • Searching in child object • Not found -> looking in inherited object • New properties of child object will hide/shadows parent property with the same name • If objects are found in parent, the property will be updated on original object
  • 9. Angular scope inheritance Normal prototypal scope inheritance in AngularJS • Ng-controller • Ng-include • Ng-switch • Directive with scope: true
  • 10. Angular scope inheritance Ng-repeat • Normal prototypal inheritance with copy/assignment • Each iteration create new child scope • Child scopes get new properties childScope = scope.$new(); // child scope prototypically inherits from parent scope ... childScope[valueIdent] = value; // creates a new childScope property
  • 11. Angular scope inheritance Directive - isolated scope (scope: {...}) • Not prototypal inheritance • Various option to access parent scopes through attributes: • '=': two-way data binding • '@': one-way data binding • '&': bind to parent expression
  • 12. Angular scope inheritance Directive - transcluded scope (transcluded: true) • Beside of isolated scope, new transcluded scope is created • New transcluded scope is inherited from parent scope • Avoid child scope hiding/shadowing parent scope's properties • Both isolated scope and transcluded scope can access to parent scope through $parent

Editor's Notes

  • #5: Nested scopes are either "child scopes" or "isolate scopes". A "child scope" (prototypically) inherits properties from its parent scope. An "isolate scope" does not
  • #6: Peculiar : normal data model -> gatekeeper of data, responsible for handling and manipulating data
  • #7: 1. The root scope is created during the application bootstrap by the $injector. During template linking, some directives create new child scopes. 2. During template linking, directives register watches on the scope. These watches will be used to propagate model values to the DOM. 3. 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. 4. 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. 5. When child scopes are no longer needed, it is the responsibility of the child scope creator to destroy them via scope.$destroy() API. This will stop propagation of $digest calls into the child scope and allow for memory used by the child scope models to be reclaimed by the garbage collector.
  • #11: For each item/iteration, ng-repeat creates a new scope, which prototypically inherits from the parent scope, but it also assigns the item's value to a new property on the new child scope.
  • #12: since the directive cannot accidentally read or modify the parent scope. <my-directive interpolated="{{parentProp1}}" twowayBinding="parentProp2"> scope: { interpolatedProp: '@interpolated', twowayBindingProp: '=twowayBinding' }
  • #13: So if your transcluded content (i.e., the stuff that ng-transclude will be replaced with) requires 2-way data binding to a primitive in the parent scope