SlideShare a Scribd company logo
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 (20)

Angular js
Angular js
Behind D Walls
 
AngularJs (1.x) Presentation
AngularJs (1.x) Presentation
Raghubir Singh
 
Introduction to AngularJS Framework
Introduction to AngularJS Framework
Raveendra R
 
AngularJS
AngularJS
Maurice De Beijer [MVP]
 
Training On Angular Js
Training On Angular Js
Mahima Radhakrishnan
 
Introduction to AngularJS
Introduction to AngularJS
Jussi Pohjolainen
 
Introduction of angular js
Introduction of angular js
Tamer Solieman
 
Angular js for beginners
Angular js for beginners
Munir Hoque
 
AngularJS for Beginners
AngularJS for Beginners
Edureka!
 
Angular JS - Introduction
Angular JS - Introduction
Sagar Acharya
 
AngularJS intro
AngularJS intro
dizabl
 
Angular js
Angular js
Arun Somu Panneerselvam
 
Angular js presentation at Datacom
Angular js presentation at Datacom
David Xi Peng Yang
 
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
Learnimtactics
 
Advanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JS
Simon Guest
 
Angular js architecture (v1.4.8)
Angular js architecture (v1.4.8)
Gabi Costel Lapusneanu
 
AngularJS: an introduction
AngularJS: an introduction
Luigi De Russis
 
AngularJS Beginners Workshop
AngularJS Beginners Workshop
Sathish VJ
 
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 Features
Mohamad Al Asmar
 
AngularJs (1.x) Presentation
AngularJs (1.x) Presentation
Raghubir Singh
 
Introduction to AngularJS Framework
Introduction to AngularJS Framework
Raveendra R
 
Introduction of angular js
Introduction of angular js
Tamer Solieman
 
Angular js for beginners
Angular js for beginners
Munir Hoque
 
AngularJS for Beginners
AngularJS for Beginners
Edureka!
 
Angular JS - Introduction
Angular JS - Introduction
Sagar Acharya
 
AngularJS intro
AngularJS intro
dizabl
 
Angular js presentation at Datacom
Angular js presentation at Datacom
David Xi Peng Yang
 
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
Learnimtactics
 
Advanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JS
Simon Guest
 
AngularJS: an introduction
AngularJS: an introduction
Luigi De Russis
 
AngularJS Beginners Workshop
AngularJS Beginners Workshop
Sathish VJ
 
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 Features
Mohamad Al Asmar
 

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

AngularJS Mobile Warsaw 20-10-2014
AngularJS Mobile Warsaw 20-10-2014
Dariusz Kalbarczyk
 
Controller in AngularJS
Controller in AngularJS
Brajesh Yadav
 
intro to Angular js
intro to Angular js
Brian Atkins
 
Angular js
Angular js
Eueung Mulyana
 
What is $root scope in angularjs
What is $root scope in angularjs
codeandyou forums
 
Introduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress Developers
Caldera Labs
 
Introduction to AngularJS
Introduction to AngularJS
Marco Vito Moscaritolo
 
Angular JS deep dive
Angular JS deep dive
Axilis
 
Angular js
Angular js
prasaddammalapati
 
Course CodeSchool - Shaping up with Angular.js
Course CodeSchool - Shaping up with Angular.js
Vinícius de Moraes
 
MeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
MeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
Simo Ahava
 
Understanding angular js $rootscope and $scope
Understanding angular js $rootscope and $scope
Brajesh Yadav
 
243329387 angular-docs
243329387 angular-docs
Abhi166803
 
Grails Advanced
Grails Advanced
Saurabh Dixit
 
Mini-Training: AngularJS
Mini-Training: AngularJS
Betclic Everest Group Tech Team
 
Let's react - Meetup
Let's react - Meetup
RAJNISH KATHAROTIYA
 
Dive into AngularJS and directives
Dive into AngularJS and directives
Tricode (part of Dept)
 
ChocolateChip-UI
ChocolateChip-UI
GeorgeIshak
 
Basics of AngularJS
Basics of AngularJS
Filip Janevski
 
Angular js vs. Facebook react
Angular js vs. Facebook react
Keyup
 
AngularJS Mobile Warsaw 20-10-2014
AngularJS Mobile Warsaw 20-10-2014
Dariusz Kalbarczyk
 
Controller in AngularJS
Controller in AngularJS
Brajesh Yadav
 
intro to Angular js
intro to Angular js
Brian Atkins
 
What is $root scope in angularjs
What is $root scope in angularjs
codeandyou forums
 
Introduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress Developers
Caldera Labs
 
Angular JS deep dive
Angular JS deep dive
Axilis
 
Course CodeSchool - Shaping up with Angular.js
Course CodeSchool - Shaping up with Angular.js
Vinícius de Moraes
 
MeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
MeasureCamp IX (London) - 10 JavaScript Concepts for web analysts
Simo Ahava
 
Understanding angular js $rootscope and $scope
Understanding angular js $rootscope and $scope
Brajesh Yadav
 
243329387 angular-docs
243329387 angular-docs
Abhi166803
 
ChocolateChip-UI
ChocolateChip-UI
GeorgeIshak
 
Angular js vs. Facebook react
Angular js vs. Facebook react
Keyup
 
Ad

More from codeandyou forums (15)

How to validate server certificate
How to validate server certificate
codeandyou forums
 
How to call $scope function from console
How to call $scope function from console
codeandyou forums
 
Understand components in Angular 2
Understand components in Angular 2
codeandyou forums
 
Understand routing in angular 2
Understand routing in angular 2
codeandyou forums
 
How to setup ionic 2
How to setup ionic 2
codeandyou forums
 
MongoDB 3.2.0 Released
MongoDB 3.2.0 Released
codeandyou forums
 
Welcome to ionic 2
Welcome to ionic 2
codeandyou forums
 
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 .pem
codeandyou forums
 
Protractor end-to-end testing framework for angular js
Protractor end-to-end testing framework for angular js
codeandyou forums
 
How routing works in angular js
How routing works in angular js
codeandyou forums
 
How to use proxy server in .net application
How to use proxy server in .net application
codeandyou forums
 
How to catch query string in angular js
How to catch query string in angular js
codeandyou forums
 
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 database
codeandyou forums
 
How to validate server certificate
How to validate server certificate
codeandyou forums
 
How to call $scope function from console
How to call $scope function from console
codeandyou forums
 
Understand components in Angular 2
Understand components in Angular 2
codeandyou forums
 
Understand routing in angular 2
Understand routing in angular 2
codeandyou forums
 
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 .pem
codeandyou forums
 
Protractor end-to-end testing framework for angular js
Protractor end-to-end testing framework for angular js
codeandyou forums
 
How routing works in angular js
How routing works in angular js
codeandyou forums
 
How to use proxy server in .net application
How to use proxy server in .net application
codeandyou forums
 
How to catch query string in angular js
How to catch query string in angular js
codeandyou forums
 
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 database
codeandyou forums
 
Ad

Recently uploaded (20)

FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
Automated Migration of ESRI Geodatabases Using XML Control Files and FME
Automated Migration of ESRI Geodatabases Using XML Control Files and FME
Safe Software
 
UPDASP a project coordination unit ......
UPDASP a project coordination unit ......
withrj1
 
Transmission Media. (Computer Networks)
Transmission Media. (Computer Networks)
S Pranav (Deepu)
 
dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Maxim Salnikov
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...
Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...
Intelli grow
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
Maharshi Mallela
 
Looking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdf
Looking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdf
Varsha Nayak
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
AI-Powered Compliance Solutions for Global Regulations | Certivo
AI-Powered Compliance Solutions for Global Regulations | Certivo
certivoai
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
What is data visualization and how data visualization tool can help.pdf
What is data visualization and how data visualization tool can help.pdf
Varsha Nayak
 
Smadav Pro 2025 Rev 15.4 Crack Full Version With Registration Key
Smadav Pro 2025 Rev 15.4 Crack Full Version With Registration Key
joybepari360
 
How to Choose the Right Web Development Agency.pdf
How to Choose the Right Web Development Agency.pdf
Creative Fosters
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Open Source Software Development Methods
Open Source Software Development Methods
VICTOR MAESTRE RAMIREZ
 
FME as an Orchestration Tool - Peak of Data & AI 2025
FME as an Orchestration Tool - Peak of Data & AI 2025
Safe Software
 
Automated Migration of ESRI Geodatabases Using XML Control Files and FME
Automated Migration of ESRI Geodatabases Using XML Control Files and FME
Safe Software
 
UPDASP a project coordination unit ......
UPDASP a project coordination unit ......
withrj1
 
Transmission Media. (Computer Networks)
Transmission Media. (Computer Networks)
S Pranav (Deepu)
 
dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Agentic Techniques in Retrieval-Augmented Generation with Azure AI Search
Maxim Salnikov
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...
Smart Financial Solutions: Money Lender Software, Daily Pigmy & Personal Loan...
Intelli grow
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
Maharshi Mallela
 
Looking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdf
Looking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdf
Varsha Nayak
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
GDG Douglas - Google AI Agents: Your Next Intern?
GDG Douglas - Google AI Agents: Your Next Intern?
felipeceotto
 
AI-Powered Compliance Solutions for Global Regulations | Certivo
AI-Powered Compliance Solutions for Global Regulations | Certivo
certivoai
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
What is data visualization and how data visualization tool can help.pdf
What is data visualization and how data visualization tool can help.pdf
Varsha Nayak
 
Smadav Pro 2025 Rev 15.4 Crack Full Version With Registration Key
Smadav Pro 2025 Rev 15.4 Crack Full Version With Registration Key
joybepari360
 
How to Choose the Right Web Development Agency.pdf
How to Choose the Right Web Development Agency.pdf
Creative Fosters
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Open Source Software Development Methods
Open Source Software Development Methods
VICTOR MAESTRE RAMIREZ
 

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