«

»

May 10

Rootscope and Scope in AngularJs

$rootscope is top-level scope. An app has only one $rootscope which will be share data among all the component of app. $rootscope is consider as global for the app. if every one want to define variable as global then he/she can use $rootscope. This method is usefull when have multiple controller in app and want to manage data from another controller. $scope for the variable define within the controller. They cannot use outside of this controller. But $rootscope for the variable which define in any of the controller and use outside of the controller. $rootscope is also known as parent scope.

Example

<html>
<head>
<script src="angular.js"></script>
<script>
var app=angular.module('myapp',[]);
app.controller('controller1',function($scope,$rootscope)
{
$scope.message='Hello Inida';
$rootscope.name="Test";
}
app.controller('controller2', function($scope,$rootscope)
{
$scope.meassage="Hello world";
$scope.mname=$rootscope.name;
}
</script>
</head>
<body ng-app="myapp">
<div ng-controller="controller1">
{{name}} <br>
{{message}}
</div>
<div ng-controller="controller2">
{{mname}}<br>
{{message}}
</div>
</body>
</html>

Output from first controller
Test
Hello India

Output from second controller
Test
Hello Wrold

Example for adding some content into list

<div ng-controller="Controller1">
<h2>Controller1 - List</h2>
<ul>
<li ng-repeat="item in list()">{{item}}</li>
</ul>
</div>
<hr />
<div ng-controller="controller2">
<h2>Ctrl2 - Add</h2>
<form ng-submit="add(newItem); newItem = '';">
<input type="text" placeholder="new item" ng-model="newItem">
<br />
<input class="btn" type="submit">
</form>
</div>
<script>
var app=angular.module('myapp',[]);
app.factory('items', function() {
var items = [];
var iService = {};
iService.add = function(item) {
items.push(item);
};
iService.list = function() {
return items;
};
return iService;
});
function controller1($scope,items) {
$scope.list = items.list;
}
function controller2($scope, items) {
$scope.add = items.add;
}
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>