0

I made a very small example that I thought would behave differently. I created two div tags nested and called their controllers ParentController and ChildController. I assigned the same variable to both ($scope.mydata}.

My expectation was that changing the child would update only the child, but changing the parent would update both. They seem to act as if they are isolated from each other.

plnkr here: http://plnkr.co/edit/zETedNQiO1hwf3ucW7wG?p=preview

<html>
<head>
    <meta charset="utf-8">
    <title>misc1</title>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
    <link rel="stylesheet" href="jquery.cluetip.css" type="text/css"/>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="script.js"></script>
</head>
<body ng-app="myapp" ng-controller="MainCtrl">

<div ng-controller="ParentController">
    <input ng-model="mydata" placeholder="Some Data">
    ... ParentController:mydata: {{ mydata }}
    <div ng-controller="ChildController">
        <input ng-model="mydata" placeholder="Some Data">
        ... ChildController:mydata: {{ mydata }}
    </div>
</div>

</body>
</html>

...

var app = angular.module('myapp', []);
app.controller('MainCtrl', function ($scope) {
});

app.controller('ParentController', function ($scope) {
    $scope.mydata = 'parent data';
});
app.controller('ChildController', function ($scope) {
    $scope.mydata = 'child data';
});
Peter Kellner
  • 14,748
  • 25
  • 102
  • 188

1 Answers1

1

The short answer is that because of prototypical inheritance the child scope shadows its parents properties.

For an in depth understanding of how this works read Mark's excellent answer What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

Community
  • 1
  • 1
Jonathan Palumbo
  • 6,851
  • 1
  • 29
  • 40
  • thanks, I think I get it. this quote I think explains it from the link you sent me. "The prototype chain is not consulted, and a new aString property is added to the childScope. This new property hides/shadows the parentScope property with the same name. This will become very important when we discuss ng-repeat and ng-include below." – Peter Kellner Oct 29 '14 at 04:34