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?
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 (thechangeRs
function inmyCtrl2
)Sharing data between controllers is what Factories/Services are very good for. In short, it works something like this.
You can see a working example in this fiddle: http://jsfiddle.net/mbielski/m8saa/
http://astutejs.blogspot.in/2015/07/angularjs-what-is-rootscope.html
There are multiple ways to achieve this one:-
1. Add
$rootScope
in.run
method2. Create one service and access it in both the controllers.
DEMO
i find no reason to do this $scope.value = $rootScope.test;
$scope is already prototype inheritance from $rootScope.
Please see this example
now you can bind this scope variable in anywhere in app tag.