2

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?

Hommer Smith
  • 26,772
  • 56
  • 167
  • 296
  • If you set `ng-model` on an `ng-options` element and bind it to `selectedItem`, for example, it will be set in the child scope and not in the controller's scope. If you use `model.selectedItem` and define `model` in the controller, it will work as you expect. – Jim Cote Apr 16 '14 at 15:14
  • 1
    See [this question](http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs). – Steve Klösters Apr 16 '14 at 15:35

1 Answers1

3

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

NicolasMoise
  • 7,261
  • 10
  • 44
  • 65
  • I would like to know why is this happening. Where is the difference between doing $scope.attr and $scope.model.attr? – Hommer Smith Apr 17 '14 at 15:24
  • Well to fully understand it you should read detailed guide on Javascript inheritance (the linked question is pretty good), but in short, when you're using a primitive, it won't update the value in parent scopes. – NicolasMoise Apr 17 '14 at 15:44
  • So, this is a primitive $scope.attribute, but this $scope.model.attribute would not be a primitive? – Hommer Smith Apr 17 '14 at 16:01