Scope is a JavaScript object that refers to the
application model. It acts as a context for evaluating angular
expressions. Basically, it acts as glue between controller and view.
Scopes are hierarchical in nature and follow the DOM structure of
your AngularJS app. AngularJS has two scope objects: $rootScope and
$scope.$scope
A $scope is a JavaScript object which is used for communication between controller and view. Basically, $scope binds a view (DOM element) to the viewmodel and functions defined in a controller.$rootScope
The $rootScope is the top-most scope. An app can have only one $rootScope which will be shared among all the components of an app. Hence it acts like a global variable. All other $scopes are children of the $rootScope.<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<title>AngularJS Filters</title>
</head>
<body ng-app="myApp">
<div ng-controller="Ctrl1" style="border:2px solid blue; padding:5px">
Hello {{msg}}!
<br />
Hello {{name}}!
(rootScope)
</div>
<br />
<div ng-controller="Ctrl2" style="border:2px solid green; padding:5px">
Hello {{msg}}!
<br />
Hey {{myName}}!
<br />
Hi {{name}}! (rootScope)
</div>
<script>
var app = angular.module('myApp', []);
app.controller('Ctrl1', function ($scope, $rootScope) {
$scope.msg = 'World';
$rootScope.name = 'AngularJS';
});
app.controller('Ctrl2', function ($scope, $rootScope) {
$scope.msg = 'Dot Net Tricks';
$scope.myName = $rootScope.name;
});
</script>
</body>
</html>
Hello World!
Hello AngularJS! (rootScope)
Hello AngularJS! (rootScope)
Hello Dot Net Tricks!
Hey AngularJS!
Hi AngularJS! (rootScope)
Hey AngularJS!
Hi AngularJS! (rootScope)
Note
- When you use ng-model with $rootScope objects then AngularJS
updates those objects under a specific $scope of a controller but not at
global level $rootScope.
- Create a private $scope for each controller to bind it to the view.
No comments:
Post a Comment