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

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?

The answer is


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.


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

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

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/


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


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/


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.


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

Examples related to angularjs

AngularJs directive not updating another directive's scope ERROR in Cannot find module 'node-sass' CORS: credentials mode is 'include' CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response WebSocket connection failed: Error during WebSocket handshake: Unexpected response code: 400 Print Html template in Angular 2 (ng-print in Angular 2) $http.get(...).success is not a function Angular 1.6.0: "Possibly unhandled rejection" error Find object by its property in array of objects with AngularJS way Error: Cannot invoke an expression whose type lacks a call signature

Examples related to angularjs-scope

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS How to call a function from another controller in angularjs? Detect if checkbox is checked or unchecked in Angular.js ng-change event $rootScope.$broadcast vs. $scope.$emit How to clear or stop timeInterval in angularjs? How do I inject a controller into another controller in AngularJS Controller not a function, got undefined, while defining controllers globally AngularJS - get element attributes values ng-if, not equal to? How to set the id attribute of a HTML element dynamically with angularjs (1.x)?

Examples related to angularjs-controller

Check if value exists in the array (AngularJS) How do I inject a controller into another controller in AngularJS Error: [ng:areq] from angular controller How do I use $rootScope in Angular to store variables? AngularJS : The correct way of binding to a service properties Using $setValidity inside a Controller AngularJS: How can I pass variables between controllers?

Examples related to rootscope

Why do we use $rootScope.$broadcast in AngularJS? How do I use $rootScope in Angular to store variables?