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

Sherin
  • 185
  • 1
  • 2
  • 10
  • Possible duplicate of [Angularjs sharing data between controllers](http://stackoverflow.com/questions/18227090/angularjs-sharing-data-between-controllers) – Martijn Welker Mar 31 '16 at 06:57

2 Answers2

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.

M. Junaid Salaat
  • 3,765
  • 1
  • 23
  • 25
  • 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? – Sherin Mar 31 '16 at 09:38
  • Nothing. You just have to call `testFactory.getName()` to retrieve your name variable in your `homeController`. See this [updated fiddle](http://jsfiddle.net/jsalaat/k3phygpz/872/) – M. Junaid Salaat Mar 31 '16 at 09:42
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.

LJ Wadowski
  • 6,424
  • 11
  • 43
  • 76