Home > Article > Web Front-end > Detailed explanation of scope in AngularJS_AngularJS
A scope is a special JavaScript object that plays the role of the controller to which its view is connected. The scope contains model data. In the controller, model data is accessed through the $scope object.
<script> var mainApp = angular.module("mainApp", []); mainApp.controller("shapeController", function($scope) { $scope.message = "In shape controller"; $scope.type = "Shape"; }); </script>
The following are important issues to consider in the example above.
Inheritance scope
Scope is specific to the controller. If we define nested controllers then the child controller will inherit the scope of its parent control.
<script> var mainApp = angular.module("mainApp", []); mainApp.controller("shapeController", function($scope) { $scope.message = "In shape controller"; $scope.type = "Shape"; }); mainApp.controller("circleController", function($scope) { $scope.message = "In circle controller"; }); </script>
The following are important issues to consider in the example above.
Example
The following example will demonstrate all the above commands.
testAngularJS.html
<html> <head> <title>Angular JS Forms</title> </head> <body> <h2>AngularJS Sample Application</h2> <div ng-app="mainApp" ng-controller="shapeController"> <p>{{message}} <br/> {{type}} </p> <div ng-controller="circleController"> <p>{{message}} <br/> {{type}} </p> </div> <div ng-controller="squareController"> <p>{{message}} <br/> {{type}} </p> </div> </div> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script> <script> var mainApp = angular.module("mainApp", []); mainApp.controller("shapeController", function($scope) { $scope.message = "In shape controller"; $scope.type = "Shape"; }); mainApp.controller("circleController", function($scope) { $scope.message = "In circle controller"; }); mainApp.controller("squareController", function($scope) { $scope.message = "In square controller"; $scope.type = "Square"; }); </script> </body> </html>
Results
Open textAngularJS.html in your web browser. See the results below.