TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
tri_inn
NA
1.2k
233.5k
AngularJS: factory and share data between controllers
Jun 12 2017 9:34 AM
My question is
AngularJS: Why people prefer factory to share data between controllers
i am new in angular. so trying to know how to share data between two controller and search google. i visited few pages and found most of the time people use factory to share data. i just like to know can't we do it by service instead of factory ?
1st example
<div ng-controller=
"FirstCtrl"
>
<input type=
"text"
ng-model=
"data.firstName"
>
<br>Input
is
: <strong>{{data.firstName}}</strong>
</div>
<hr>
<div ng-controller=
"SecondCtrl"
>
Input should also be here: {{data.firstName}}
</div>
myApp.factory(
'MyService'
, function(){
return
{
data: {
firstName:
''
,
lastName:
''
},
update: function(first, last) {
// Improve this method as needed
this
.data.firstName = first;
this
.data.lastName = last;
}
};
});
// Your controller can use the service's update method
myApp.controller(
'SecondCtrl'
, function($scope, MyService){
$scope.data = MyService.data;
$scope.updateData = function(first, last) {
MyService.update(first, last);
}
});
2nd example
var myApp = angular.module(
'myApp'
, []);
myApp.factory(
'Data'
, function(){
var service = {
FirstName:
''
,
setFirstName: function(name) {
// this is the trick to sync the data
// so no need for a $watch function
// call this from anywhere when you need to update FirstName
angular.copy(name, service.FirstName);
}
};
return
service;
});
// Step 1 Controller
myApp.controller(
'FirstCtrl'
, function( $scope, Data ){
});
// Step 2 Controller
myApp.controller(
'SecondCtrl'
, function( $scope, Data ){
$scope.FirstName = Data.FirstName;
});
examples are taken from this url https://stackoverflow.com/questions/21919962/share-data-between-angularjs-controllers
please guide me.
Reply
Answers (
1
)
angularjs create directory and pass path to API
AngularJS: service and factory is singleton ?