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;
}
6
  • Inject $rootScope dependency in your controllers. Commented Sep 19, 2013 at 6: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..!) Commented Sep 19, 2013 at 6: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. Commented Sep 19, 2013 at 6:29
  • Thank you Chandermani. Following works. function Ctrl1($rootScope) { $rootScope.value = "asdf"; } function Ctrl2($rootScope, $scope) { $scope.value = $rootScope.value; } Commented Sep 19, 2013 at 6:36
  • 3
    Sharing same data between controllers means sharing data via service . You can use factory for this. Commented Jun 5, 2014 at 5:27

2 Answers 2

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

you get the point :)

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

Comments

1

If you are trying to show the variable in the view, there is not need of assign the variable from $rootScope to $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.