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:
- the
controller2
inherits properties ofcontroller1
because insidecontroller1
- at beginning none of scopes have
message
property, undefined - when click on first button,
controller1
has propertymessage
inheritcontroller2
(so both display message value) - when click on second button,
controller2
overrides property creating propertymessage
- since here, both controllers have
message
propertycontroller2
has overridden property in scope, doesn't show anymore value ofcontroller1
's property, if click again on first button
you can verify following:
- click @ first on second button.
controller2
has propertymessage
- the parent cannot access properties of children,
message
parent property still undefined - click on first button , see first value has been assigned
controller1
too, without changing 1 ofcontroller2
i hope makes sense
Comments
Post a Comment