AngularJS Scope


Angular JS has two kinds of scopes.

  • $scope: The $scope is available in local(within controller).

  • $rootScope: The rootScope is available in the entire application.

If a variable has the same name in both the current scope and in the rootScope, the application use the one in the current scope.

$scope

The scope is the binding part between the HTML (view) and the JavaScript (controller). Scope is nothing but a object which can hold variables and methods. Vlues can be passed from controller to HTML.

The $scope object is a function an argument, for controller

<script>
	var app = angular.module('myApp', []);

	app.controller('myCtrl', function($scope) {
		$scope.place = "TamilNadu";
	});
</script>

When adding properties to the $scope object in the controller, the view (HTML) gets access to these properties. In the view, you do not use the prefix $scope, just refer to a propertyname, like {{place}}.

$rootScope

All applications have a $rootScope which is the scope created on the HTML element that contains the ng-app directive.

<script>
	var app = angular.module('myApp', []);
	app.run(function($rootScope) {
		$rootScope.place = 'India';
	});
</script>
Angular JS example with rootScope and scope
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp">
		<p>You are from(If foreigner ask):</p>
		<h1>{{place}}</h1>

		<div ng-controller="myCtrl">
			<p>You are from (If other indian asks)</p>
			<h1>{{place}}</h1>
		</div>

		<p>You are from:</p>
		<h1>{{place}}</h1>

		<script>
			var app = angular.module('myApp', []);
			app.run(function($rootScope) {
				$rootScope.place = 'India';
			});
			app.controller('myCtrl', function($scope) {
				$scope.place = "TamilNadu";
			});
		</script>

</body>
</html>

When you are under controller, values will be taken from $scope which is local to myCtrl. Otherthan controller which is trying access same object value will be taken from global to Angular app(myapp)