3

I want to assign some data to a global variable (may be $rootscope) which gets initialized at pageload. And then I want to access that data from all the controllers. How would I do that?

// Edit : I tried following and it works as expected....

function Ctrl1($rootScope) {
    $rootScope.value = "asdf";
}

function Ctrl2($rootScope, $scope) {
    $scope.value = $rootScope.value;
}
exAres
  • 4,806
  • 16
  • 53
  • 95
  • Inject `$rootScope` dependency in your controllers. – Chandermani Sep 19 '13 at 06:15
  • Thanks for quick reply Chandermani. Will $rootscope remain common across all the controllers? I mean can I assign something to it in one controller function and access it back from the other controller function? Sorry, I am very new to angularjs (2days old..!) – exAres Sep 19 '13 at 06:17
  • 1
    Yes absolutely! You can alway try it out. `$rootScope` is the thing closest to global variable in Angular and hence it's use should be minimized. There are other ways to share data, search for angular services. – Chandermani Sep 19 '13 at 06:29
  • Thank you Chandermani. Following works. function Ctrl1($rootScope) { $rootScope.value = "asdf"; } function Ctrl2($rootScope, $scope) { $scope.value = $rootScope.value; } – exAres Sep 19 '13 at 06:36
  • 3
    Sharing same data between controllers means sharing data via service . You can use factory for this. – Anil Arya Jun 05 '14 at 05:27
  • yes, thanks. Later I figured out that using factory was the best option. – exAres Jun 05 '14 at 06:11

2 Answers2

6
MyController($rootScope,$scope)
{
  $rootScope = ....
}

you get the point :)

CodeSamurai777
  • 3,285
  • 2
  • 24
  • 42
1

If you are trying to show the variable in the view, there is not need of assign the variable from $rootScope to $scope.

julian
  • 374
  • 2
  • 11