The scope is the binding part between the JavaScript (controller) and the HTML (view).
If we consider an AngularJS application to consist of:
- Model – which is the data available for the current view.
- View – which is the HTML.
- Controller – which is the JavaScript function that controls/makes/changes/removes the data.
Then the scope is the Model.
A scope is a JavaScript object with properties and methods, which are available for the view and the controller both.
$scope object pass as an argument, when we make a controller in AngularJS.
Example
Open the Example1.html file and add the code in it.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script> <title></title> </head> <body> <div ng-app="myApp" ng-controller="myCtrl"> <h2>{{title}}</h2> </div> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function ($scope) { $scope.title = "The CodeHubs"; }); </script> </body> </html>
If we make changes in the view, the model and the controller will be updated automatically:
Application explained:
- The ng-app=”myApp” directive tells that the <div> element is the “owner” of an AngularJS application.
- The ng-controller=”myCtrl” is defined as a JavaScript object with $scope as an argument.
- The $scope refers to application which uses the myCtrl object.
- When adding properties to the $scope object in the controller, the view (HTML) gets access to these properties automatically.
- In the view, we just refer to a property name (like {{title}}), we don’t have to use the prefix $scope.
Output:
Root Scope
All applications have a $rootScope. The rootScope is available in the entire application. $rootScope is the scope created on the HTML element that holds the ng-app directive.
If a variable has the same name in both the rootScope and in the current scope, the application uses the one in the current scope.
Example
Open the Example1.html file and add the code in it.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.min.js"></script> <title></title> </head> <body ng-app="myApp"> <h1>{{title}}</h1> <div ng-controller="myCtrl"> <h1>{{title}}</h1> </div> <h1>{{title}}</h1> <script> var app = angular.module('myApp', []); app.run(function ($rootScope) { $rootScope.title = 'The rootScope'; }); app.controller('myCtrl', function ($scope) { $scope.title = "The Current Scope"; }); </script> </body> </html>
A variable named “title” exists in both the rootScope and in the controller’s scope.
Output: