AngularJS > Scope

Controller scope Inheritence in AngularJS

How the scope inheritence of the controllers works in AngularJS?

The scope inheritence works in the same way as it works in other programming language or in normal real life scenarios. Let's see below example to understand.

    var app = angular.module('app', []);
    app.controller('GrandFatherController', ['$scope', function($scope) {
        $scope.GrandSirname = 'Mehta';
        $scope.Name = 'Ram Dhyan ';

    app.controller('FatherController', ['$scope', function($scope) {
        $scope.FatherSirname = 'Narayan';
        $scope.Name = 'Sheo ';

    app.controller('ChildController', ['$scope', function($scope) {
        $scope.Name = 'Shreeharsh';


    <p>Controller Inheritance</p>
    <div ng-app="app" ng-controller="GrandFatherController">
        Grand father name : {{ Name }} {{ GrandSirname }}

        <div ng-controller="FatherController">
        Father name : {{ Name }} {{ FatherSirname }}
                    {{ GrandSirname }}

            <div ng-controller="ChildController">
            Child name : {{ Name }} {{ FatherSirname }}
                    {{ GrandSirname }}

In this code snippet, focus on JavaScript code. We have three controllers

  1. GrandFatherController - the grand controller that is in the super scope
  2. FatherController - the parent controller, child to the GrandFatherController
  3. ChildController - the child of ParentController and grand child of GrandFatherController

First two controller has their own Sirname values set.

  • The child controller inherit the sir name of FatherController as well as GrandFatherController.
  • The Father controller inherit the sir name of GrandFather controller only.

Now notice the HTML code template that in arranged in the order of controller declared. The ChildController is nested in FatherController that in tern is nested in GrandFatherController.

Now see the result below. The Name is coming from their respective controller however FatherSirname in the ChildController is inherited from FatheController and GrandSirname is inherited from GrandFatherController. Similarly, In FatherControler, GrandSirname is inherited from GrandFatherController.


Controller inheritance in AngularJS

 Views: 11671 | Post Order: 19

Write for us

Hosting Recommendations