0

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??

1

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

my question is to set $scopename=Admin and want it to call from home page as {{$scopename}}.Then what I have to change in your above code?
Nothing. You just have to call testFactory.getName() to retrieve your name variable in your homeController. See this updated fiddle
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.