SlideShare a Scribd company logo
1 of 12
How to share data between controllers in
AngularJs
Some time we need to share data between controllers. Today I am showing
different way to sharedata between controllers.
Share data between controllers in
AngularJs with $rootScope
Plnkr - http://plnkr.co/edit/QFH62vsWwvJTuCxfNE46?p=preview
<!DOCTYPE html>
<html>
<head>
<title>Share data between controllers in AngularJs with $rootScope</title>
<link rel="stylesheet"
href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css">
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.js"></scri
pt>
<script>
var app = angular.module("myApp", []);
app.run(function($rootScope) {
$rootScope.userData = {};
$rootScope.userData.firstName = "Ravi";
$rootScope.userData.lastName = "Sharma";
});
app.controller("firstController", function($scope, $rootScope) {
});
app.controller("secondController", function($scope, $rootScope) {
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="firstController">
<br>
<input type="text" ng-model="userData.firstName">
<br>
<input type="text" ng-model="userData.lastName">
<br>
<br>First Name: <strong>{{userData.firstName}}</strong>
<br>Last Name : <strong>{{userData.lastName}}</strong> </div>
<hr>
<div ng-controller="secondController"> Showing first name and last name on
second controller: <b> {{userData.firstName}} {{userData.lastName}}</b>
</div>
</body>
</html>
Example
Share data between controllers in
AngularJs using factory
Plnkr - http://plnkr.co/edit/O3h3Vh1nGjo810vjvJA4?p=preview
<!DOCTYPE html>
<html>
<head>
<title>Share data between controllers in AngularJs using factory</title>
<link rel="stylesheet"
href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css">
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.js"></scri
pt>
<script>
var app = angular.module("myApp", []);
app.factory('userFactory', function() {
return {
userData: {
firstName: '',
lastName: ''
}
};
});
app.controller("firstController", function($scope, userFactory) {
$scope.data = userFactory.userData;
$scope.data.firstName="Ravi";
$scope.data.lastName="Sharma";
});
app.controller("secondController", function($scope, userFactory) {
$scope.data = userFactory.userData;
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="firstController">
<br>
<input type="text" ng-model="data.firstName"><br>
<input type="text" ng-model="data.lastName">
<br>
<br>First Name: <strong>{{data.firstName}}</strong>
<br>Last Name : <strong>{{data.lastName}}</strong>
</div>
<hr>
<div ng-controller="secondController"> Showing first name and last name on
second controller: <b> {{data.firstName}} {{data.lastName}}</b> </div>
</body>
</html>
Example
Share data between controllers in
AngularJs with Factory Update Function
Plnkr - http://plnkr.co/edit/bXwR4SOP3Nx9zlCVFUFe?p=preview
<!DOCTYPE html>
<html>
<head>
<title>Share data between controllers in AngularJs with Factory Update
Function</title>
<link rel="stylesheet"
href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css">
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.js"></scri
pt>
<script>
var app = angular.module("myApp", []);
app.factory('userFactory', function() {
return {
userData: {
firstName: '',
lastName: ''
},
updateUserData: function(first, last) {
this.userData.firstName = first;
this.userData.lastName = last;
}
};
});
app.controller("firstController", function($scope, userFactory) {
$scope.data = userFactory.userData;
$scope.updateInfo = function(first, last) {
userFactory.updateUserData(first, last);
};
});
app.controller("secondController", function($scope, userFactory) {
$scope.data = userFactory.userData;
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="firstController">
<br>
<input type="text" ng-model="firstName"><br>
<input type="text" ng-model="lastName"><br>
<button ng-click="updateInfo(firstName,lastName)">Update</button>
<br>
<br>First Name: <strong>{{data.firstName}}</strong>
<br>Last Name : <strong>{{data.lastName}}</strong>
</div>
<hr>
<div ng-controller="secondController"> Showing first name and last name on
second controller: <b> {{data.firstName}} {{data.lastName}}</b> </div>
</body>
</html>
Example
Share data between controllers in
AngularJs with factory and $watch
function
Plnkr -http:/plnkr.co/edit/rQcYsI1MoVsgM967MwzY?p=preview
<!DOCTYPE html>
<html>
<head>
<title>Share data between controllers in AngularJs with factory and $watch
function</title>
<link rel="stylesheet"
href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css">
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.js"></scri
pt>
<script>
var app = angular.module("myApp", []);
app.factory('userFactory', function() {
var empData = {
FirstName: ''
};
return {
getFirstName: function () {
return empData.FirstName;
},
setFirstName: function (firstName,lastName) {
empData.FirstName = firstName;
}
};
});
app.controller("firstController", function($scope, userFactory) {
$scope.firstName = '';
$scope.lastName = '';
$scope.$watch('firstName', function (newValue, oldValue) {
if (newValue !== oldValue)
userFactory.setFirstName(newValue);
});
});
app.controller("secondController", function($scope, userFactory) {
$scope.$watch(function ()
{ return userFactory.getFirstName();
},
function (newValue, oldValue) {
if (newValue !== oldValue)
$scope.firstName = newValue;
});
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="firstController">
<br>
<input type="text" ng-model="firstName"><br>
<br>
<br>First Name: <strong>{{firstName}}</strong>
</div>
<hr>
<div ng-controller="secondController">
Showing first name and last name on second controller: <b> {{firstName}}
</b> </div>
</body>
</html>
Example
Share data between controllers in
AngularJs with complex object using
$watch
Plnkr - http://plnkr.co/edit/8gQI7im5JjF6Zb9tL1Vb?p=preview
<!DOCTYPE html>
<html>
<head>
<title>Share data between controllers in AngularJs with complex object
using $watch</title>
<link rel="stylesheet"
href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css">
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.js"></scri
pt>
<script>
var app = angular.module("myApp", []);
app.factory('userFactory', function() {
var empData = {
FirstName: '',
LastName: ''
};
return {
getEmployee: function() {
return empData;
},
setEmployee: function(firstName, lastName) {
empData.FirstName = firstName;
empData.LastName = lastName;
}
};
});
app.controller("firstController", function($scope, userFactory) {
$scope.Emp = {
firstName: '',
lastName: ''
}
$scope.$watch('Emp', function(newValue, oldValue) {
if (newValue !== oldValue) {
userFactory.setEmployee(newValue.firstName,
newValue.lastName);
}
}, true); //JavaScript use "reference" to check equality when we
compare two complex objects. Just pass [objectEquality] "true" to $watch
function.
});
app.controller("secondController", function($scope, userFactory) {
$scope.Emp = {
firstName: '',
firstName: ''
}
$scope.$watch(function() {
return userFactory.getEmployee();
}, function(newValue, oldValue) {
if (newValue !== oldValue) $scope.Emp.firstName =
newValue.FirstName;
$scope.Emp.lastName = newValue.LastName;
}, true);
});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="firstController">
<br>
<input type="text" ng-model="Emp.firstName">
<br>
<input type="text" ng-model="Emp.lastName">
<br>
<br>
<br> First Name: <strong>{{Emp.firstName}}</strong>
<br>Last Name: <strong>{{Emp.lastName}}</strong> </div>
<hr>
<div ng-controller="secondController"> Showing first name and last name on
second controller: First Name - <strong> {{Emp.firstName}} </strong>, Last
Name: <strong>{{Emp.lastName}}</strong> </div>
</body>
</html>
Example
Thanks
www.codeandyou.com
http://www.codeandyou.com/2015/09/share-data-
between-controllers-in-angularjs.html
Keywords - How to share data between controllers in AngularJs, share data in
angularjs, share data between controllers

More Related Content

What's hot

AngularJs (1.x) Presentation
AngularJs (1.x) PresentationAngularJs (1.x) Presentation
AngularJs (1.x) PresentationRaghubir Singh
 
Introduction to AngularJS Framework
Introduction to AngularJS FrameworkIntroduction to AngularJS Framework
Introduction to AngularJS FrameworkRaveendra R
 
Introduction of angular js
Introduction of angular jsIntroduction of angular js
Introduction of angular jsTamer Solieman
 
Angular js for beginners
Angular js for beginnersAngular js for beginners
Angular js for beginnersMunir Hoque
 
AngularJS for Beginners
AngularJS for BeginnersAngularJS for Beginners
AngularJS for BeginnersEdureka!
 
Angular JS - Introduction
Angular JS - IntroductionAngular JS - Introduction
Angular JS - IntroductionSagar Acharya
 
AngularJS intro
AngularJS introAngularJS intro
AngularJS introdizabl
 
Angular js presentation at Datacom
Angular js presentation at DatacomAngular js presentation at Datacom
Angular js presentation at DatacomDavid Xi Peng Yang
 
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosAngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosLearnimtactics
 
Advanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JSAdvanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JSSimon Guest
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introductionLuigi De Russis
 
AngularJS Beginners Workshop
AngularJS Beginners WorkshopAngularJS Beginners Workshop
AngularJS Beginners WorkshopSathish VJ
 
AngularJS - What is it & Why is it awesome ? (with demos)
AngularJS - What is it & Why is it awesome ? (with demos)AngularJS - What is it & Why is it awesome ? (with demos)
AngularJS - What is it & Why is it awesome ? (with demos)Gary Arora
 
AngularJS: Overview & Key Features
AngularJS: Overview & Key FeaturesAngularJS: Overview & Key Features
AngularJS: Overview & Key FeaturesMohamad Al Asmar
 

What's hot (20)

Angular js
Angular jsAngular js
Angular js
 
AngularJs (1.x) Presentation
AngularJs (1.x) PresentationAngularJs (1.x) Presentation
AngularJs (1.x) Presentation
 
Introduction to AngularJS Framework
Introduction to AngularJS FrameworkIntroduction to AngularJS Framework
Introduction to AngularJS Framework
 
AngularJS
AngularJSAngularJS
AngularJS
 
Training On Angular Js
Training On Angular JsTraining On Angular Js
Training On Angular Js
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Introduction of angular js
Introduction of angular jsIntroduction of angular js
Introduction of angular js
 
Angular js for beginners
Angular js for beginnersAngular js for beginners
Angular js for beginners
 
AngularJS for Beginners
AngularJS for BeginnersAngularJS for Beginners
AngularJS for Beginners
 
Angular JS - Introduction
Angular JS - IntroductionAngular JS - Introduction
Angular JS - Introduction
 
AngularJS intro
AngularJS introAngularJS intro
AngularJS intro
 
Angular js
Angular jsAngular js
Angular js
 
Angular js presentation at Datacom
Angular js presentation at DatacomAngular js presentation at Datacom
Angular js presentation at Datacom
 
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosAngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
 
Advanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JSAdvanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JS
 
Angular js architecture (v1.4.8)
Angular js architecture (v1.4.8)Angular js architecture (v1.4.8)
Angular js architecture (v1.4.8)
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introduction
 
AngularJS Beginners Workshop
AngularJS Beginners WorkshopAngularJS Beginners Workshop
AngularJS Beginners Workshop
 
AngularJS - What is it & Why is it awesome ? (with demos)
AngularJS - What is it & Why is it awesome ? (with demos)AngularJS - What is it & Why is it awesome ? (with demos)
AngularJS - What is it & Why is it awesome ? (with demos)
 
AngularJS: Overview & Key Features
AngularJS: Overview & Key FeaturesAngularJS: Overview & Key Features
AngularJS: Overview & Key Features
 

Similar to Different way to share data between controllers in angular js

AngularJS Mobile Warsaw 20-10-2014
AngularJS Mobile Warsaw 20-10-2014AngularJS Mobile Warsaw 20-10-2014
AngularJS Mobile Warsaw 20-10-2014Dariusz Kalbarczyk
 
Controller in AngularJS
Controller in AngularJSController in AngularJS
Controller in AngularJSBrajesh Yadav
 
intro to Angular js
intro to Angular jsintro to Angular js
intro to Angular jsBrian Atkins
 
What is $root scope in angularjs
What is $root scope in angularjsWhat is $root scope in angularjs
What is $root scope in angularjscodeandyou forums
 
Introduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress DevelopersIntroduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress DevelopersCaldera Labs
 
Angular JS deep dive
Angular JS deep diveAngular JS deep dive
Angular JS deep diveAxilis
 
Course CodeSchool - Shaping up with Angular.js
Course CodeSchool - Shaping up with Angular.jsCourse CodeSchool - Shaping up with Angular.js
Course CodeSchool - Shaping up with Angular.jsVinícius de Moraes
 
MeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
MeasureCamp IX (London) - 10 JavaScript Concepts for web analystsMeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
MeasureCamp IX (London) - 10 JavaScript Concepts for web analystsSimo Ahava
 
Understanding angular js $rootscope and $scope
Understanding angular js $rootscope and $scopeUnderstanding angular js $rootscope and $scope
Understanding angular js $rootscope and $scopeBrajesh Yadav
 
243329387 angular-docs
243329387 angular-docs243329387 angular-docs
243329387 angular-docsAbhi166803
 
ChocolateChip-UI
ChocolateChip-UIChocolateChip-UI
ChocolateChip-UIGeorgeIshak
 
Angular js vs. Facebook react
Angular js vs. Facebook reactAngular js vs. Facebook react
Angular js vs. Facebook reactKeyup
 

Similar to Different way to share data between controllers in angular js (20)

AngularJS Mobile Warsaw 20-10-2014
AngularJS Mobile Warsaw 20-10-2014AngularJS Mobile Warsaw 20-10-2014
AngularJS Mobile Warsaw 20-10-2014
 
Controller in AngularJS
Controller in AngularJSController in AngularJS
Controller in AngularJS
 
intro to Angular js
intro to Angular jsintro to Angular js
intro to Angular js
 
Angular js
Angular jsAngular js
Angular js
 
What is $root scope in angularjs
What is $root scope in angularjsWhat is $root scope in angularjs
What is $root scope in angularjs
 
Introduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress DevelopersIntroduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress Developers
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Angular JS deep dive
Angular JS deep diveAngular JS deep dive
Angular JS deep dive
 
Angular js
Angular jsAngular js
Angular js
 
Course CodeSchool - Shaping up with Angular.js
Course CodeSchool - Shaping up with Angular.jsCourse CodeSchool - Shaping up with Angular.js
Course CodeSchool - Shaping up with Angular.js
 
MeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
MeasureCamp IX (London) - 10 JavaScript Concepts for web analystsMeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
MeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
 
Understanding angular js $rootscope and $scope
Understanding angular js $rootscope and $scopeUnderstanding angular js $rootscope and $scope
Understanding angular js $rootscope and $scope
 
243329387 angular-docs
243329387 angular-docs243329387 angular-docs
243329387 angular-docs
 
Grails Advanced
Grails Advanced Grails Advanced
Grails Advanced
 
Mini-Training: AngularJS
Mini-Training: AngularJSMini-Training: AngularJS
Mini-Training: AngularJS
 
Let's react - Meetup
Let's react - MeetupLet's react - Meetup
Let's react - Meetup
 
Dive into AngularJS and directives
Dive into AngularJS and directivesDive into AngularJS and directives
Dive into AngularJS and directives
 
ChocolateChip-UI
ChocolateChip-UIChocolateChip-UI
ChocolateChip-UI
 
Basics of AngularJS
Basics of AngularJSBasics of AngularJS
Basics of AngularJS
 
Angular js vs. Facebook react
Angular js vs. Facebook reactAngular js vs. Facebook react
Angular js vs. Facebook react
 

More from codeandyou forums

How to validate server certificate
How to validate server certificateHow to validate server certificate
How to validate server certificatecodeandyou forums
 
How to call $scope function from console
How to call $scope function from consoleHow to call $scope function from console
How to call $scope function from consolecodeandyou forums
 
Understand components in Angular 2
Understand components in Angular 2Understand components in Angular 2
Understand components in Angular 2codeandyou forums
 
Understand routing in angular 2
Understand routing in angular 2Understand routing in angular 2
Understand routing in angular 2codeandyou forums
 
What is JSON? Why use JSON? JSON Types? JSON Helpful Tools?
What is JSON? Why use JSON? JSON Types? JSON Helpful Tools?What is JSON? Why use JSON? JSON Types? JSON Helpful Tools?
What is JSON? Why use JSON? JSON Types? JSON Helpful Tools?codeandyou forums
 
How to install ssl certificate from .pem
How to install ssl certificate from .pemHow to install ssl certificate from .pem
How to install ssl certificate from .pemcodeandyou forums
 
Protractor end-to-end testing framework for angular js
Protractor   end-to-end testing framework for angular jsProtractor   end-to-end testing framework for angular js
Protractor end-to-end testing framework for angular jscodeandyou forums
 
How routing works in angular js
How routing works in angular jsHow routing works in angular js
How routing works in angular jscodeandyou forums
 
How to use proxy server in .net application
How to use proxy server in .net applicationHow to use proxy server in .net application
How to use proxy server in .net applicationcodeandyou forums
 
How to catch query string in angular js
How to catch query string in angular jsHow to catch query string in angular js
How to catch query string in angular jscodeandyou forums
 
How to set up a proxy server on windows
How to set up a proxy server on windows How to set up a proxy server on windows
How to set up a proxy server on windows codeandyou forums
 
How to save log4net into database
How to save log4net into databaseHow to save log4net into database
How to save log4net into databasecodeandyou forums
 

More from codeandyou forums (15)

How to validate server certificate
How to validate server certificateHow to validate server certificate
How to validate server certificate
 
How to call $scope function from console
How to call $scope function from consoleHow to call $scope function from console
How to call $scope function from console
 
Understand components in Angular 2
Understand components in Angular 2Understand components in Angular 2
Understand components in Angular 2
 
Understand routing in angular 2
Understand routing in angular 2Understand routing in angular 2
Understand routing in angular 2
 
How to setup ionic 2
How to setup ionic 2How to setup ionic 2
How to setup ionic 2
 
MongoDB 3.2.0 Released
MongoDB 3.2.0 ReleasedMongoDB 3.2.0 Released
MongoDB 3.2.0 Released
 
Welcome to ionic 2
Welcome to ionic 2Welcome to ionic 2
Welcome to ionic 2
 
What is JSON? Why use JSON? JSON Types? JSON Helpful Tools?
What is JSON? Why use JSON? JSON Types? JSON Helpful Tools?What is JSON? Why use JSON? JSON Types? JSON Helpful Tools?
What is JSON? Why use JSON? JSON Types? JSON Helpful Tools?
 
How to install ssl certificate from .pem
How to install ssl certificate from .pemHow to install ssl certificate from .pem
How to install ssl certificate from .pem
 
Protractor end-to-end testing framework for angular js
Protractor   end-to-end testing framework for angular jsProtractor   end-to-end testing framework for angular js
Protractor end-to-end testing framework for angular js
 
How routing works in angular js
How routing works in angular jsHow routing works in angular js
How routing works in angular js
 
How to use proxy server in .net application
How to use proxy server in .net applicationHow to use proxy server in .net application
How to use proxy server in .net application
 
How to catch query string in angular js
How to catch query string in angular jsHow to catch query string in angular js
How to catch query string in angular js
 
How to set up a proxy server on windows
How to set up a proxy server on windows How to set up a proxy server on windows
How to set up a proxy server on windows
 
How to save log4net into database
How to save log4net into databaseHow to save log4net into database
How to save log4net into database
 

Recently uploaded

ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 

Recently uploaded (20)

ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 

Different way to share data between controllers in angular js

  • 1. How to share data between controllers in AngularJs
  • 2. Some time we need to share data between controllers. Today I am showing different way to sharedata between controllers. Share data between controllers in AngularJs with $rootScope Plnkr - http://plnkr.co/edit/QFH62vsWwvJTuCxfNE46?p=preview <!DOCTYPE html> <html> <head> <title>Share data between controllers in AngularJs with $rootScope</title> <link rel="stylesheet" href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.js"></scri pt> <script> var app = angular.module("myApp", []); app.run(function($rootScope) { $rootScope.userData = {}; $rootScope.userData.firstName = "Ravi"; $rootScope.userData.lastName = "Sharma"; }); app.controller("firstController", function($scope, $rootScope) { }); app.controller("secondController", function($scope, $rootScope) { }); </script> </head> <body ng-app="myApp"> <div ng-controller="firstController"> <br> <input type="text" ng-model="userData.firstName"> <br> <input type="text" ng-model="userData.lastName"> <br> <br>First Name: <strong>{{userData.firstName}}</strong> <br>Last Name : <strong>{{userData.lastName}}</strong> </div> <hr>
  • 3. <div ng-controller="secondController"> Showing first name and last name on second controller: <b> {{userData.firstName}} {{userData.lastName}}</b> </div> </body> </html> Example
  • 4. Share data between controllers in AngularJs using factory Plnkr - http://plnkr.co/edit/O3h3Vh1nGjo810vjvJA4?p=preview <!DOCTYPE html> <html> <head> <title>Share data between controllers in AngularJs using factory</title> <link rel="stylesheet" href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.js"></scri pt> <script> var app = angular.module("myApp", []); app.factory('userFactory', function() { return { userData: { firstName: '', lastName: '' } }; }); app.controller("firstController", function($scope, userFactory) { $scope.data = userFactory.userData; $scope.data.firstName="Ravi"; $scope.data.lastName="Sharma"; }); app.controller("secondController", function($scope, userFactory) { $scope.data = userFactory.userData; }); </script> </head> <body ng-app="myApp"> <div ng-controller="firstController"> <br> <input type="text" ng-model="data.firstName"><br> <input type="text" ng-model="data.lastName"> <br>
  • 5. <br>First Name: <strong>{{data.firstName}}</strong> <br>Last Name : <strong>{{data.lastName}}</strong> </div> <hr> <div ng-controller="secondController"> Showing first name and last name on second controller: <b> {{data.firstName}} {{data.lastName}}</b> </div> </body> </html> Example
  • 6. Share data between controllers in AngularJs with Factory Update Function Plnkr - http://plnkr.co/edit/bXwR4SOP3Nx9zlCVFUFe?p=preview <!DOCTYPE html> <html> <head> <title>Share data between controllers in AngularJs with Factory Update Function</title> <link rel="stylesheet" href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.js"></scri pt> <script> var app = angular.module("myApp", []); app.factory('userFactory', function() { return { userData: { firstName: '', lastName: '' }, updateUserData: function(first, last) { this.userData.firstName = first; this.userData.lastName = last; } }; }); app.controller("firstController", function($scope, userFactory) { $scope.data = userFactory.userData; $scope.updateInfo = function(first, last) { userFactory.updateUserData(first, last); }; }); app.controller("secondController", function($scope, userFactory) { $scope.data = userFactory.userData; }); </script> </head> <body ng-app="myApp"> <div ng-controller="firstController">
  • 7. <br> <input type="text" ng-model="firstName"><br> <input type="text" ng-model="lastName"><br> <button ng-click="updateInfo(firstName,lastName)">Update</button> <br> <br>First Name: <strong>{{data.firstName}}</strong> <br>Last Name : <strong>{{data.lastName}}</strong> </div> <hr> <div ng-controller="secondController"> Showing first name and last name on second controller: <b> {{data.firstName}} {{data.lastName}}</b> </div> </body> </html> Example
  • 8. Share data between controllers in AngularJs with factory and $watch function Plnkr -http:/plnkr.co/edit/rQcYsI1MoVsgM967MwzY?p=preview <!DOCTYPE html> <html> <head> <title>Share data between controllers in AngularJs with factory and $watch function</title> <link rel="stylesheet" href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.js"></scri pt> <script> var app = angular.module("myApp", []); app.factory('userFactory', function() { var empData = { FirstName: '' }; return { getFirstName: function () { return empData.FirstName; }, setFirstName: function (firstName,lastName) { empData.FirstName = firstName; } }; }); app.controller("firstController", function($scope, userFactory) { $scope.firstName = ''; $scope.lastName = ''; $scope.$watch('firstName', function (newValue, oldValue) { if (newValue !== oldValue) userFactory.setFirstName(newValue); });
  • 9. }); app.controller("secondController", function($scope, userFactory) { $scope.$watch(function () { return userFactory.getFirstName(); }, function (newValue, oldValue) { if (newValue !== oldValue) $scope.firstName = newValue; }); }); </script> </head> <body ng-app="myApp"> <div ng-controller="firstController"> <br> <input type="text" ng-model="firstName"><br> <br> <br>First Name: <strong>{{firstName}}</strong> </div> <hr> <div ng-controller="secondController"> Showing first name and last name on second controller: <b> {{firstName}} </b> </div> </body> </html> Example
  • 10. Share data between controllers in AngularJs with complex object using $watch Plnkr - http://plnkr.co/edit/8gQI7im5JjF6Zb9tL1Vb?p=preview <!DOCTYPE html> <html> <head> <title>Share data between controllers in AngularJs with complex object using $watch</title> <link rel="stylesheet" href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css"> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.js"></scri pt> <script> var app = angular.module("myApp", []); app.factory('userFactory', function() { var empData = { FirstName: '', LastName: '' }; return { getEmployee: function() { return empData; }, setEmployee: function(firstName, lastName) { empData.FirstName = firstName; empData.LastName = lastName; } }; });
  • 11. app.controller("firstController", function($scope, userFactory) { $scope.Emp = { firstName: '', lastName: '' } $scope.$watch('Emp', function(newValue, oldValue) { if (newValue !== oldValue) { userFactory.setEmployee(newValue.firstName, newValue.lastName); } }, true); //JavaScript use "reference" to check equality when we compare two complex objects. Just pass [objectEquality] "true" to $watch function. }); app.controller("secondController", function($scope, userFactory) { $scope.Emp = { firstName: '', firstName: '' } $scope.$watch(function() { return userFactory.getEmployee(); }, function(newValue, oldValue) { if (newValue !== oldValue) $scope.Emp.firstName = newValue.FirstName; $scope.Emp.lastName = newValue.LastName; }, true); }); </script> </head> <body ng-app="myApp"> <div ng-controller="firstController"> <br> <input type="text" ng-model="Emp.firstName"> <br> <input type="text" ng-model="Emp.lastName"> <br> <br> <br> First Name: <strong>{{Emp.firstName}}</strong> <br>Last Name: <strong>{{Emp.lastName}}</strong> </div> <hr> <div ng-controller="secondController"> Showing first name and last name on second controller: First Name - <strong> {{Emp.firstName}} </strong>, Last Name: <strong>{{Emp.lastName}}</strong> </div> </body> </html> Example
  • 12. Thanks www.codeandyou.com http://www.codeandyou.com/2015/09/share-data- between-controllers-in-angularjs.html Keywords - How to share data between controllers in AngularJs, share data in angularjs, share data between controllers