Understanding scope inheritance in AngularJS

29 dec. 2023
Intermediate
19,9K Views
2 min read  

The $scope object used by views in AngularJS are organized into a hierarchy. There is a root scope, and the $rootScope can has one or more child scopes. Each controller has its own $scope (which is a child of the $rootScope), so whatever variables you create on $scope within controller, these variables are accessible by the view based on this controller. For a deeper understanding of scopes, controllers, and other essential AngularJS concepts, consider exploring an Angular certification Training program.

For example, suppose you have two controllers: ParentController and ChildController as given below:

<!DOCTYPE html>
<html>
<head>
 <title>Angular Scope Inheritance</title>
 <script src="lib/angular.js"></script>
 <script>
 var app = angular.module('ScopeChain', []);

 app.controller("parentController", function ($scope) {
 $scope.managerName = 'Shailendra Chauhan';
 $scope.$parent.companyName = 'Dot Net Tricks'; //attached to $rootScope
 });
 app.controller("childController", function ($scope, $controller) {
 $scope.teamLeadName = 'Deepak Chauhan';
 });
 </script>
</head>
<body ng-app="ScopeChain">
 <div ng-controller="parentController ">
 <table style="border:2px solid #e37112">
 <caption>Parent Controller</caption>
 <tr>
 <td>Manager Name</td>
 <td>{{managerName}}</td>
 </tr>
 <tr>
 <td>Company Name</td>
 <td>{{companyName}}</td>
 </tr>
 <tr>
 <td>
 <table ng-controller="childController" style="border:2px solid #428bca">
 <caption>Child Controller</caption>
 <tr>
 <td>Team Lead Name</td>
 <td>{{ teamLeadName }}</td>
 </tr>
 <tr>
 <td>Reporting To</td>
 <td>{{managerName}}</td>
 </tr>
 <tr>
 <td>Company Name</td>
 <td>{{companyName}}</td>
 </tr>
 </table>
 </td>
 </tr>
 </table>
 </div>
</body>
</html>

How it works...

What do you think?

I hope you will enjoy the AngularJS scope hierarchy while developing your app with AngularJS. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome. For those interested in gaining a comprehensive understanding of AngularJS scope hierarchy and other core concepts, consider exploring an angular certification course

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Learn to Crack Your Technical Interview

Accept cookies & close this