angularjs - controller 2 will receive value from controller 1 only once. why? -


i wondering if explain behavior of angular test application.

in html, have controller 2 inside controller 1.

when click on "click on me 1" w/o having clicked on "click on me 2", $scope.message of controller 2 receives "clicked 1" value.

then, click on "click on me 2". if click on "click on me 1" again, $scope.message of controller 2 not receive "clicked 1" value anymore.

i have theory, hear experts.

thanks.

var app = angular.module("myapp", []);  app.controller("controller1", function($scope, $http, $filter) {    $scope.message = "clicked none";    $scope.clicked = function() {      $scope.message = 'clicked 1';    };  });      angular.module("myapp").controller('controller2', function($scope) {    vm = this;    vm.clicked = clicked;      function clicked() {      $scope.message = 'clicked 2';    }  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>  <div ng-app="myapp">    <div ng-controller="controller1">      <div>        i'm in c1 {{ message}}        <button type="button" ng-click='clicked()'>click me c1!</button>          <div ng-controller="controller2 c2">          i'm in c2 {{ message }}          <button type="button" ng-click='c2.clicked()'>click me c2!</button>        </div>      </div>    </div>

in angularjs, inner controllers inherit parent controller if used in way did, , inherit properties.

so in sample happening:

  1. the controller2 inherits properties of controller1 because inside controller1
  2. at beginning none of scopes have message property, undefined
  3. when click on first button, controller1 has property message inherit controller2 (so both display message value)
  4. when click on second button, controller2 overrides property creating property message
  5. since here, both controllers have message property controller2 has overridden property in scope, doesn't show anymore value of controller1's property, if click again on first button

you can verify following:

  1. click @ first on second button. controller2 has property message
  2. the parent cannot access properties of children, message parent property still undefined
  3. click on first button , see first value has been assigned controller1 too, without changing 1 of controller2

i hope makes sense


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -