$rootScope is the global scope which acts as the parent
for all the controllers $scope,
values set in one controller’s $scope can be accessed in other controllers
$scope across the application.
The following example defines 2 controllers, the 1st controller sets value for the variable rootValue and the 2nd controller accesses the value from the rootScope and displays it in the view.
Controller Scripts
var app = angular.module("myApp", [])
app.controller("rootScopeController1", function($scope, $rootScope) {
$rootScope.rootValue = "Value from rootScopeController1";
});
app.controller("rootScopeController2", function($scope, $rootScope) {
$scope.globalValue = $rootScope.rootValue;
});
View
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title>AngularJS - Basic</title>
</head>
<body>
<div ng-controller="rootScopeController1" style="color:red">
</div>
<div ng-controller="rootScopeController2" style="color:green;">
{{globalValue}}
</div>
<script src="angular.min.js"></script>
<script src="rootScope.js"></script>
</body>
</html>
The following example defines 2 controllers, the 1st controller sets value for the variable rootValue and the 2nd controller accesses the value from the rootScope and displays it in the view.
Controller Scripts
var app = angular.module("myApp", [])
app.controller("rootScopeController1", function($scope, $rootScope) {
$rootScope.rootValue = "Value from rootScopeController1";
});
app.controller("rootScopeController2", function($scope, $rootScope) {
$scope.globalValue = $rootScope.rootValue;
});
View
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title>AngularJS - Basic</title>
</head>
<body>
<div ng-controller="rootScopeController1" style="color:red">
</div>
<div ng-controller="rootScopeController2" style="color:green;">
{{globalValue}}
</div>
<script src="angular.min.js"></script>
<script src="rootScope.js"></script>
</body>
</html>
No comments:
Post a Comment