Nested Controller In Angular JS

Nested Controller in Angular Js In this article we discuss about how to get main controller object or value in child controller. I am not going to discuss here what is angular js controller. Some time in interview such type of question asked by interviewer. Here we make a two controller one is main controller and second is subcontroller which is inside of main controller. Now suppose in code we set title variable in both controller & want to access main controller title variable to subcontroller. I Here is complete code about above scenario you have to just copy paste & execute it.

Nested Controller in Angualr JS

<!DOCTYPE html>
<head lang="en">
 <script src=""></script>
   angular.module('app', []);
   angular.module('app').controller("MainController", function($scope){
   $scope.title = 'I am Parent Controller Title';
   angular.module('app').controller("SubController", function($scope){
    $scope.title = 'I am Sub-Controller Title';
<body ng-app='app' ng-controller='MainController'>
<div class='container'>
  <p style="color:Red">Angular JS Main Controller - {{title}}</p>
  <div ng-controller='SubController'>
    <p style="color:green">
      Angular JS SUB Controller - {{title}}</p>
    <p style="color:blue">Angular JS Call Main Controller object inside child controller - {{$parent.title}}</p>

Output of nested controller example in Angualr JS

Angular JS Main Controller - I am Parent Controller Title
Angular JS SUB Controller - I am Sub-Controller Title
Angular JS Call Main Controller object inside child controller - I am Parent Controller Title


Post a Comment