The jsFiddle for this question can be found here: http://jsfiddle.net/Hsw9F/1/
JavaScript (console.log debug information available in the jsFiddle)
var app = angular.module('StackOverflow',[]);
function ParentController($scope) {
$scope.parentCounter = 5;
}
function ChildController($scope) {
$scope.childCounter = $scope.parentCounter;
$scope.increaseCounters = function() {
++$scope.parentCounter;
++$scope.childCounter;
};
}
In the example above I have a counter in the parent and the child controllers named parentCounter and childCounter respectively. I’ve also provided a function in the child controller named increaseCounters() that increases both counters by one.
Both of these counters are displayed on the page:
<div ng-app="StackOverflow">
<div ng-controller="ParentController">
Parent Counter: {{parentCounter}}<br />
<div ng-controller="ChildController">
Child Counter: {{childCounter}}<br />
<a href="javascript:void(0)"
ng-click="increaseCounters()">Increase Counters</a>
</div><!-- END ChildController -->
</div><!-- END ParentController -->
</div><!-- END StackOverflow app -->
The problem is that AngularJS doesn’t seem to update the {{parentCounter}} on the page, and only updates the {{childCounter}} when the increase counters function is called. Is there anything I have overlooked?
++$scope.parentCounter;creates a child scope property with nameparentCounterthat hides/shadows the parent scope property of the same name.Add
console.log($scope);to your increaseCounters() function to see it.One workaround:
++$scope.$parent.parentCounter;The problem you are experiencing has to do with the way JavaScript prototypal inheritance works. I suggest reading What are the nuances of scope prototypal / prototypical inheritance in AngularJS? — it has some nice pictures explaining what happens when primitives are created in child scopes.