How do I use $rootScope in Angular to store variables?

trysis picture trysis · Sep 18, 2013 · Viewed 377.8k times · Source

How do I use $rootScope to store variables in a controller I want to later access in another controller? For example:

angular.module('myApp').controller('myCtrl', function($scope) {
  var a = //something in the scope
  //put it in the root scope
});

angular.module('myApp').controller('myCtrl2', function($scope) {
  var b = //get var a from root scope somehow
  //use var b
});

How would I do this?

Answer

Jason picture Jason · Sep 18, 2013

Variables set at the root-scope are available to the controller scope via prototypical inheritance.

Here is a modified version of @Nitish's demo that shows the relationship a bit clearer: http://jsfiddle.net/TmPk5/6/

Notice that the rootScope's variable is set when the module initializes, and then each of the inherited scope's get their own copy which can be set independently (the change function). Also, the rootScope's value can be updated too (the changeRs function in myCtrl2)

angular.module('myApp', [])
.run(function($rootScope) {
    $rootScope.test = new Date();
})
.controller('myCtrl', function($scope, $rootScope) {
  $scope.change = function() {
        $scope.test = new Date();
    };

    $scope.getOrig = function() {
        return $rootScope.test;
    };
})
.controller('myCtrl2', function($scope, $rootScope) {
    $scope.change = function() {
        $scope.test = new Date();
    };

    $scope.changeRs = function() {
        $rootScope.test = new Date();
    };

    $scope.getOrig = function() {
        return $rootScope.test;
    };
});