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

AngularjsAngularjs ScopeAngularjs ControllerRootscope

Angularjs Problem Overview


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?

Angularjs Solutions


Solution 1 - Angularjs

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;
    };
});

Solution 2 - Angularjs

Sharing data between controllers is what Factories/Services are very good for. In short, it works something like this.

var app = angular.module('myApp', []);

app.factory('items', function() {
    var items = [];
    var itemsService = {};
    
    itemsService.add = function(item) {
        items.push(item);
    };
    itemsService.list = function() {
        return items;
    };
    
    return itemsService;
});

function Ctrl1($scope,items) {
    $scope.list = items.list; 
}

function Ctrl2($scope, items) {
    $scope.add = items.add;
}

You can see a working example in this fiddle: http://jsfiddle.net/mbielski/m8saa/

Solution 3 - Angularjs

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

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

   $scope.value = $rootScope.test;
   alert($scope.value);

 //    var b = $rootScope.test;
 //  alert(b);
 });

DEMO

Solution 4 - Angularjs

i find no reason to do this $scope.value = $rootScope.test;

$scope is already prototype inheritance from $rootScope.

Please see this example

var app = angular.module('app',[]).run(function($rootScope){
$rootScope.userName = "Rezaul Hasan";
});

now you can bind this scope variable in anywhere in app tag.

Solution 5 - Angularjs

first store the values in $rootScope as

.run(function($rootScope){
$rootScope.myData = {name : "nikhil"}
})

.controller('myCtrl', function($scope) {
var a ="Nikhilesh";
$scope.myData.name = a;
});

.controller('myCtrl2', function($scope) {
var b = $scope.myData.name;
)}

$rootScope is the parent of all $scope, each $scope receives a copy of $rootScope data which you can access using $scope itself.

Solution 6 - Angularjs

If it is just "access in other controller" then you can use angular constants for that, the benefit is; you can add some global settings or other things that you want to access throughout application

app.constant(‘appGlobals’, {
    defaultTemplatePath: '/assets/html/template/',
    appName: 'My Awesome App'
});

and then access it like:

app.controller(‘SomeController’, [‘appGlobals’, function SomeController(config) {
    console.log(appGlobals);
    console.log(‘default path’, appGlobals.defaultTemplatePath);
}]);

(didn't test)

more info: http://ilikekillnerds.com/2014/11/constants-values-global-variables-in-angularjs-the-right-way/

Solution 7 - Angularjs

http://astutejs.blogspot.in/2015/07/angularjs-what-is-rootscope.html</a>

 app.controller('AppCtrl2', function ($scope, $rootScope) {
     $scope.msg = 'SCOPE';
     $rootScope.name = 'ROOT SCOPE';
 });

Solution 8 - Angularjs

There are multiple ways to achieve this one:-

1. Add $rootScope in .run method

.run(function ($rootScope) {
    $rootScope.name = "Peter";
});

// Controller
.controller('myController', function ($scope,$rootScope) {
    console.log("Name in rootscope ",$rootScope.name);
    OR
    console.log("Name in scope ",$scope.name);
});

2. Create one service and access it in both the controllers.

.factory('myFactory', function () {
     var object = {};

     object.users = ['John', 'James', 'Jake']; 

     return object;
})
// Controller A

.controller('ControllerA', function (myFactory) {
    console.log("In controller A ", myFactory);
})

// Controller B

.controller('ControllerB', function (myFactory) {
    console.log("In controller B ", myFactory);
})

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontrysisView Question on Stackoverflow
Solution 1 - AngularjsJasonView Answer on Stackoverflow
Solution 2 - AngularjsMBielskiView Answer on Stackoverflow
Solution 3 - AngularjsNitish KumarView Answer on Stackoverflow
Solution 4 - AngularjsroconmachineView Answer on Stackoverflow
Solution 5 - AngularjsNikhilesh YadavView Answer on Stackoverflow
Solution 6 - AngularjsRaza AhmedView Answer on Stackoverflow
Solution 7 - AngularjssathishView Answer on Stackoverflow
Solution 8 - Angularjsojus kulkarniView Answer on Stackoverflow