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.

Example:

<!DOCTYPE html>
<html>
<head>
 <script src="
  https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js">
 </script>
</head>
<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/> 
    	</div>
    </div>
 
    <script>
        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";
        });
    </script>
</body>
</html>

Try it:

JS Bin on jsbin.com