Reputation: 185
I have Two modules namely Authentication and Home and they have there own controllers.each of them have same name controllers.js
I have to display value like $scope.username in home page (module Home) which is comes from controller of module Authentication .How it possible??
Upvotes: 0
Views: 387
Reputation: 6720
You can use shared service instead which will return your value and the in your controller(s) inject that service as dependency.
e.g.
angular.module( 'yourApp' )
.value("username", "Jon")
.controller("index", ["$scope", "username", function($scope, username) {
$scope.username = username;
}]);
or by use of factory recipe:
angular.module( 'yourApp' )
.factory("username", function(){
var value = 'John';
return {
get: function(){
return value;
},
set: function(newName){
value = newName;
}
}
})
.controller("index", ["$scope", "username", function($scope, username) {
$scope.username = username.get();
}]);
If this value will be dynamic you can save value as object and return reference, then you won't need to use manually created watches to see if value changed:
angular.module( 'yourApp' )
.factory("username", function(){
var username = {
value: 'John'
};
return {
get: function(){
return username;
},
set: function(newName){
username.value = newName;
}
}
})
.controller("index", ["$scope", "username", function($scope, username) {
$scope.usernameObj = username.get();
}]);
and in view:
{{usernameObj.value}}
you can also do that by use of prototypical inheritance of $scope
by saving value in parent scope.
Upvotes: 0
Reputation: 3783
There are many ways. I would prefer you to make an app.factory('dataFactory' , func(){..})
and get/set
data there and retrieve your value in any module through out the app.
app.factory('testFactory', function(){
var _name = '';
return {
getName: function(text){
return _name;
},
setName: function(name){
_name = name;
}
}
});
Working Fiddle
Hope it helps.
Upvotes: 2