Step 4-AngularJS Scopes

Definition – Scope is an object which is used to call JavaScript functions and properties.
Scope is used in both view(html) and controller(JavaScript).

Types of scopes- There are two scopes in AngularJS.

1- $scope – This is used for current view(one html).
2- $rootscope – This is used for all views(entire application).

Now look on below example-

<!DOCTYPE html>
<html ng-app="myApp">
	<meta charset="UTF-8">
	<title>AngularJS Scope Example</title>
	<script src=""></script>
<body ng-controller="myController">
	<h1>{{ message }}</h1>
	<p>Current view count: {{ count }}</p>
	<p>Total count: {{ totalCount }}</p>

	<button ng-click="incrementCount()">Increment Current Count</button>
	<button ng-click="incrementTotalCount()">Increment Total Count</button>

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

		app.controller('myController', ['$scope', '$rootScope', function($scope, $rootScope) {
			$scope.message = "Welcome to AngularJS Scope Example";
			$scope.count = 0;
			$rootScope.totalCount = 0;

			$scope.incrementCount = function() {

			$scope.incrementTotalCount = function() {

In this example, we have defined an AngularJS module named myApp. We have also defined a controller named myController that uses both $scope and $rootScope.

Inside the myController, we have defined two variables: count and totalCount. count is a variable that is specific to the current view and is defined using $scope. totalCount is a variable that is common to all views and is defined using $rootScope.

We have also defined two functions: incrementCount() and incrementTotalCount(). The incrementCount() function increments the count variable, while the incrementTotalCount() function increments the totalCount variable.

In the HTML, we have used the ng-click directive to call these functions when the buttons are clicked. We have also used the {{ }} syntax to display the values of message, count, and totalCount on the page.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.