Santosh Yalla Santosh Yalla - 2 months ago 13
AngularJS Question

My AngularJS scope is not working as expected

I'm a newbie to AngularJS. I was working with the basic scope concept.

In my code, there is a Parent Controller and Child Controller.

View

<div ng-controller="ParentController">
<input type="text" ng-model="name">
<p>
This is parent : {{name}}
</p>
<div ng-controller="ChildController">
<input type="text" ng-model="name">
<p>
This is child : {{name}}
</p>
</div>
</div>


Controller

angular.module('myApp').controller('ParentController',['$scope',function($scope){
$scope.name='Santosh';
}]);

angular.module('myApp').controller('ChildController',['$scope',function($scope){
}]);


If you change the value in one textbox, the value in other textbox should be changed.

But, in the above code, if I change value of the Parent TextBox, it's working as expected. But if I change value of second textbox, the change is not reflected.

Please help me with this issue.

Answer

This is Scope Hierarchy problem. You can solve it by using dot notation.

View

<div ng-controller="ParentController">
    <input type="text" ng-model="model.name">
    <p>
        This is parent : {{model.name}}
    </p>
    <div ng-controller="ChildController">
        <input type="text" ng-model="model.name">
        <p>
            This is child : {{model.name}}
        </p>
    </div>
</div>

Controller

angular.module('myApp').controller('ParentController',['$scope',function($scope){
        $scope.model={
            name :'Santosh'
        };
}]);

angular.module('myApp').controller('ChildController',['$scope',function($scope){
}]);

Hope your problem is resolved now... :-)