Easy learning with example program codes

Angularjs scope inheritance tutorial

AngularJS scope inheritance:

In case of multiple controllers AngularJS framework creates and pass a different $scope object to each controller so that data and methods of one controller not be accessed in another controller. AngularJS also provides the inheritance feature for nested controllers. For nested controllers child controllers can inherit and override the parent’s controller properties but vice-versa is not true.

Example Explanation:

First include the AngularJS library in the application. The ng-app directive initializes the application. The ng-controller directive defines the controller. We defined two controllers here and set their properties using $scope object. The child controller inherit the message property and overrides the color property from parent controller. It also add “type” property which not be available for parent controller.


<!DOCTYPE html>
 <script src="">
<body ng-app="testApp">
<h1>AngularJS Scope Inheritance Example.</h1>
    <div ng-controller="parentController">
      	Controller Name: {{controllerName}}<br/>
        Message: {{message}}<br/>
      	Color: {{color}}<br/>
      	<div ng-controller="childController">
      		Controller Name: {{controllerName}}<br/>
        	Message: {{message}}<br/>
          	Color: {{color}}<br/>
            Type: {{type}}<br/> 
        var ngApp = angular.module('testApp', []);
        ngApp.controller('parentController', function ($scope) {
          	$scope.controllerName = "parentController"; 
            $scope.message = "Hello world!"; 
            $scope.color = "Blue";
       ngApp.controller('childController', function ($scope) {
         	$scope.controllerName = "childController";
            $scope.color = "Blue";
         	$scope.type = "Child";

Try it:

JS Bin on

Please follow and like us:

Copyright © 2020 CodesJava Protection Status