Reading the ng-book, there is a part that suggest that when using the $scope
, try to wrap the attributes within another attribute, like this:
$scope.model.attribute
instead of $scope.attribute
According to the author this will be helpful if we have nested controllers as if we don't do it this way, if we were to change the value in the child $scope, it wouldn't go up to the parent.
I don't think I understand why is this necessary? What is the difference between $scope.model.attribute
and $scope.attribute
in terms of prototypal inheritance?
please see this fiddle I've made to illustrate this issue.
http://jsfiddle.net/nicolasmoise/X9KYU/4/
HTML:
<body ng-app="myApp">
<div ng-controller="parentCtrl">
<!--{{message}}<input type="text" ng-model="message">-->
{{obj.message}}<input type="text" ng-model="obj.message">
<div ng-controller="childCtrl">
<!--{{message}}<input type="text" ng-model="message">-->
{{obj.message}}<input type="text" ng-model="obj.message">
</div>
</div>
</body>
Controller:
//Switch between commented/uncommented
angular.module('myApp', [])
.controller('parentCtrl', ['$scope', function($scope){
//$scope.message="Hello";
$scope.obj={message:"Hello"}
}])
.controller('childCtrl', ['$scope', function($scope){
}]);
If you use a "primitive" ($scope.message
), editing it from the child controller will not change the value in the parent controller.
As you say, it all has to do with Javascript's prototypical inheritance