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';
});
-
read the link hereharishr– harishr2014年10月29日 03:04:11 +00:00Commented Oct 29, 2014 at 3:04
1 Answer 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?