This specific scenario is extracted from the book titled ng-book: The complete book on AngularJS. I need some clarification on the outcome presented in the following example.
<div ng-controller="SomeController">
{{ someBareValue }}
<button ng-click="someAction()">Communicate to child</button>
<div ng-controller="ChildController">
{{ someBareValue }}
<button ng-click="childAction()">Communicate to parent</button>
</div>
</div>
angular.module('myApp', [])
.controller('SomeController', function($scope) {
// anti-pattern, bare value
$scope.someBareValue = 'hello computer';
// set actions on $scope itself, this is okay
$scope.someAction = function() {
// sets {{ someBareValue }} inside SomeController and ChildController
$scope.someBareValue = 'hello human, from parent';
};
})
.controller('ChildController', function($scope) {
$scope.childAction = function() {
// sets {{ someBareValue }} inside ChildController
$scope.someBareValue = 'hello human, from child';
};
});
The example is available at:
In explanation provided in the book, it states
Due to the mechanism of prototypal inheritance with value objects in JavaScript, altering someBareValue using an action in the parent affects it in the child as well, but the reverse is not true. To observe this issue firsthand, attempt clicking on the child button before engaging with the parent button. This sequence illustrates that the child controller holds a duplicate, not a direct reference to someBareValue.
My confusion lies in: If you follow the book's guidance by selecting "Communicate to parent" initially and then proceeding with "Communicate to child", the latter cannot modify the text within the child component.
Interestingly, if the parent button is clicked first, it unlocks the capability to alter the child text thereafter.
I struggle to comprehend why the order of clicks impacts the outcome of the parent button and what role exactly prototypal inheritance plays in this particular case?