Angular JS - Nested Controllers

  •   In HTML DOM can be created in hierarchy(Parent and child DOM elements).
  •   Same way, Angular JS controllers also attached to the DOM hierarchy.
  •   Obviously these are the Nested controllers.
  •   The variable $scope will be created for the respective controller.
  •   Intresting point here is, The $scope variable will have the access to the  properties and methods to the higher $scope hierarchy.


 Nested Controllers

    <div ng-controller="ParentController" ng-app="nestedControllers">
    <p>{{prefix}} {{ctrl}}</p>

    <div ng-controller="ChildController">
      <p>{{prefix}} {{ctrl}}</p>

      <div ng-controller="GrandChildController">
        <p>{{prefix}} {{ctrl}}</p>

  $scope hierarchy

    var myApp = angular.module('nestedControllers', []);
    myApp.controller('ParentController', ['$scope', function($scope) {
      $scope.ctrl = 'ParentController';
      $scope.prefix = 'I am'; //overrides in the child controllers
    myApp.controller('ChildController', ['$scope', function($scope) {
      $scope.ctrl = 'ChildController';
    myApp.controller('GrandChildController', ['$scope', function($scope) {
      $scope.ctrl = 'GrandChildController';

No comments

Powered by Blogger.