Reputation: 8429
Please have a look at https://plnkr.co/edit/j6S9pKL8sLVdSZNFNe9z?p=preview
<body >
<h4>Try me </h4> <input placeholder="top box" ng-model='address' />
<div ng-controller="ToddlerCtrl">
<h4>Try me </h4>
<input placeholder="box2" ng-model='address' /> - {{address}}
<input placeholder="box3" ng-model='address' />
</div>
<div ng-controller="otherCtrl">
<h4>Try me </h4>
<input placeholder="box4" ng-model='address' /> - {{address}}
<input placeholder="box5" ng-model='address' />
</div>
Box 2,3 are bound to each other it makes sense. Box 4,5 are bound to each other it makes sense.
But first input box is bound to all others, and it keeps bound only as long as we do not type something directly in its following boxes.
The one who is directly provided a value looses its binding to top box.
I am unable to break binding of top (first) box with others, without typing something in it following boxes, keeping its model name same (address) and keeping the first box at same scope
Upvotes: 0
Views: 71
Reputation: 131
http://www.angularjshub.com/examples/basics/nestedcontrollers/
Defining variables directly on the $scope objects managed by the controllers can have unexpected behaviors if we don't know how AngularJS works.
Working with object variables:https://plnkr.co/edit/mQDFg2pM5u3cjuhDgha4?p=preview Try me Try me - {{address}}
<div ng-controller="otherCtrl">
<h4>Try me </h4>
<input placeholder="box4" ng-model='firstModelObj.address' /> - {{address}}
<input placeholder="box5" ng-model='firstModelObj.address' />
</div>
Upvotes: 1
Reputation: 6620
You can remove the ng-controller
form body to another div to make each binding different. Now each binding will be happening in the scope of each controllers. If you nest controllers, the parent scopes value will be reflected in the scopes of the child controller. This is one way to do it by maintaining the same ng-model
names. Alternative will be change to the name of the model for parent controller outerCtrl
to something else
<body>
<div ng-controller='outerCtrl'>
<h4>Try me </h4> <input placeholder="top box" ng-model='address' />
</div>
<div ng-controller="ToddlerCtrl">
<h4>Try me </h4>
<input placeholder="box2" ng-model='address' /> - {{address}}
<input placeholder="box3" ng-model='address' />
</div>
<div ng-controller="otherCtrl">
<h4>Try me </h4>
<input placeholder="box4" ng-model='address' /> - {{address}}
<input placeholder="box5" ng-model='address' />
</div>
</body>
Update:
When you type something in the first input irrespective of the input being inside a controller or not(for your case) , the value will bind to $scope.$parent
and that is reflected across everywhere. But if you change the ng-model
for your controllers, the binding is happening in $scope
of that controller. Now the value of address in $scope
and $scope.$parent
are different and any change in $scope of a controller won't affect the parent scope.
Updated Demo: https://plnkr.co/edit/xG6nY8yTR3AoNkeHex0E?p=preview
Upvotes: 1