$rootScope is a parent scope of all $scope and can be shared to all $scope.
Size: 292.67 KB
Language: en
Added: Sep 09, 2015
Slides: 4 pages
Slide Content
What is $rootScope in
AngularJs
$rootScope is a parent scope of all $scope and can be shared to all $scope.
One application can have only one $rootScope.
$scope is a JavaScript object associated to controller but $rootScope is not.
Scopes provide separation between model and the view.
For use of $rootScope need to inject into controller.
Methods and properties created in the $scope object are only accessed inside same controller in
view.
All other scopes are descendant scopes of the root scope.
<!DOCTYPE html>
<html>
<head>
<title>Share data between controllers in AngularJs with $rootScope</title>
<link rel="stylesheet"
href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css ">
<script
src="https://ajax.googleapis.com/ajax/ libs/angularjs/1.2.4/angular.js "></scri
pt>
<script>
var app = angular.module("myApp", []);
app.run(function($rootScope) {
$rootScope.userData = {};
$rootScope.userData.firstName = "Ravi";
$rootScope.userData.lastNa me = "Sharma";
});
app.controller("firstController", function($scope, $rootScope) {});
app.controller("secondController", function($scope, $rootScope) {});
</script>
</head>
<body ng-app="myApp">
<div ng-controller="firstController">
<br>
<input type="text" ng-model="userData.firstName">
<br>
<input type="text" ng-model="userData.lastName">
<br>
<br>First Name: <strong>{{userData.firstName}}</strong>
<br>Last Name : <strong>{{ userData.lastName}}</strong> </div>
<hr>
<div ng-controller="secondController"> Showing first name and last name on
second controller: <b>
{{userData.firstName}} {{userData.lastName}}</b> </div>
</body>