SlideShare une entreprise Scribd logo
1  sur  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

Contenu connexe

Tendances

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
 

Tendances (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
 

Similaire à 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
 

Similaire à 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
 

Plus de 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
 

Plus de 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
 

Dernier

Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
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
 
(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
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
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
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 

Dernier (20)

Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
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...
 
(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...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
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...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 

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