Sunday, 2 April 2017

How to use properties of the nested Controllers ?


EXAMPLE

JS
app.controller("myController", function ($scope) {
   $scope.message = "My message"
;
});

app.controller("fatherController", function ($scope) {
   $scope.message = "Papa's message"
;
});


app.controller("grandFatherController", function ($scope) {
   $scope.message = "Grandpa's message"
;
});



HTML 1. NESTED CONTROLLERS


<div ng-controller="myController"
    {{ message }}
    <div ng-controller="fatherController">
       {{ message }}
       <div ng-controller="grandFatherController">
         {{ message }}
       </div>
    </div>
</div>

Output
My message
Papa's message
Grandpa's message



HTML 2. NESTED CONTROLLERS USING $parent

<div ng-controller="myController"
   {{ message }}
   <div ng-controller="fatherController">
      {{ $parent.message }} - {{ message }}
      <div ng-controller="grandFatherController">
        {{ $parent.$parent.message }} - {{ $parent.message }} - {{ message }}
      </div>
   </div>
</div>


Output
My message
My message - Papa's message
My message - Papa's message - Grandpa's message



HTML 3. NESTED CONTROLLERS USING ALIAS : MORE READABLE

<div ng-controller="myController as myCtrl"
   {{ myCtrl.message }}
   <div ng-controller="fatherController as fatherCtrl">
      {{ myCtrl.message }} - {{ fatherCtrl.message }}
      <div ng-controller="grandFatherController as grandFatherCtrl">
        {{ myCtrl.message }} - {{ fatherCtrl.message }} - {{ grandFatherCtrl.message }}
      </div>
   </div>
</div>


Output
My message
My message - Papa's message
My message - Papa's message - Grandpa's message

No comments:

Post a Comment

Note: only a member of this blog may post a comment.