Nested Controller In Angular JS

By
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>
<html>
<head lang="en">
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
 <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';
    });
</script>
</head>
<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>
   </div>
</div>
</body>
</html>

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

0 comments:

Post a Comment