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';
});
asked Oct 29, 2014 at 3:02
1
  • read the link here Commented Oct 29, 2014 at 3:04

1 Answer 1

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?

answered Oct 29, 2014 at 3:47
Sign up to request clarification or add additional context in comments.

1 Comment

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."

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.