How do I use $rootScope in Angular to store variables?
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;
};
});
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/
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
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.
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.