0
votes

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';
});
1
read the link hereharishr

1 Answers

1
votes

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?