
In this article, we will discuss about Angular scope, controller and scope inheritance which is always chaos for many developers.
In terms of AngularJs, a controller is a JavaScript constructor function that is used to enhance the AngualarJs Scope. AngularJs Controller is defined using the ng-controller directive, which is used to control the flow of data in the application. AngularJS application completely relies on controllers for handling data. Generally, a controller holds only the business logic needed for a single view.
Controllers are used to basically control the data in any MVC pattern application, In same way with AngularJS Controller control the flow of data in the application.
Today, we will delve into the parent-child controller relationship or scope inheritance and passing data among controllers of AngularJS. There are several cases where we might need to pass data among the controllers, as it is a common requirement of any application.
For every controller with ng-controller directive in AngularJS, it creates a new child scope and then forms a hierarchy of scopes that can inherit from each other. The $scope that each controller receives will have access to properties and methods defined by controllers higher up the hierarchy.
In other words, every child controller will have access to its parents $scope or any upper-level controller. However, rootscope can be access by every controllers.
Let us depict this with an illustration.

In the above image, there are 4 controllers. Their hierarchy is as shown below,
- Parent Controller >> Child A Controller
- Parent Controller >> Child B Controller >> GrandChild Controller
- Child A and Child B can access the methods and properties with $scopes of Parent Controller. However, Child A and Child B will not be able to share their $scopes under this concept.
- Similarly, GrandChild Controller will be able to access the $scope of Child B and Parent Controller as they are at higher level of this controller.
Additionally, each and every child controller (inner) can manipulate the $scope of the parent controller (upper).
Sample Code
App.js
- (function(angular) {
- 'use strict';
- var rijapp = angular.module('parentChild', []);
- rijapp.controller('ParentController', ['$scope', function($scope) {
- $scope.name = 'Parent';
- $scope.shareparentname = "Hey, This is from Parent";
- }]);
- rijapp.controller('ChildAController', ['$scope', function($scope) {
- $scope.name = 'Child A';
- }]);
- rijapp.controller('ChildBController', ['$scope', function($scope) {
- $scope.name = 'Child B';
- $scope.sharechildname = "Hey, This is from Child B";
- }]);
- rijapp.controller('GrandChildController', ['$scope', function($scope) {
- $scope.name = 'Grand Child';
- }]);
- })(window.angular);


Suraj KumarPosted Jan 28, 2021, 5:34 AM
Keep sharing like this article.
Satya KarkiPosted Jan 27, 2021, 5:53 PM
Nice article Rijwan thanks for sharing.