Click here to Skip to main content
15,899,126 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello All,
Please help me on bellow issue.
I have declare & assign a value in rootscope valrible & want to acces from another controller but it say undefine in controller 2.
Controller 1
$rootScope.name = 'anonymous';


controller2
$scope.local = $rootScope.name;
       alert($scope.local);


But showing undefined, am i missing any configuration?

What I have tried:

Controller 1
<pre> $rootScope.name = 'anonymous';


controller2
$scope.local = $rootScope.name;
       alert($scope.local);
Posted
Updated 18-Feb-17 6:02am

1. Please ensure you have injected $rootScope in both the controllers.
2. If you are updating it's value, wrap it in $rootScope.$apply(), so Angular will know something is going on and do its binding.

$rootScope.$apply(function () {               
    $rootScope.name = 'anonymous';
  });
 
Share this answer
 
v2
You shouldn't be polluting `$rootScope` inside angular application. Because `$rootScope` is topmost `root` of application. If you define any variable over it, it will available on any child scope. When it comes to variable sharing among-est different components of Angular, you should consider using service/factory. They are singleton object which will be available throughout the application.

app.service('sharedData', sharedDataService)
function sharedDataService(){
   var self = this;
   self.getName = getName;
   self.setName = setName;
   function setName(name) {
      self.name = name;
   }
   functName(nam = namee) {
      return self.name;
   }
}

//Controller 1
$scope.local = sharedData.getName();

//Controller 2
sharedData.setName('anonymous')
$scope.getName = sharedData.getName;

//On view
You could use `{{getName()}}`
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900