Monday, May 12, 2014

AngularJS Two Way Data Binding Only Works One Way Error

There is a problem with two way data binding in AngularJS where the data binding only works one way. This happens when the HTML element bound to the data is inside an automatically created child scope (e.g. inside an ng-include or ng-repeat block).

Let's say the following code is within an ng-include block:


<input ng-model="valueX" />

If $scope.valueX is set as "100" in the controller, it will show "100" in the input box above. However, if the user updates the value, this value won't be reflected in "$scope.valueX", because in this case the child scope will create a copy of that, different from the parent scope value. This results in two way data binding only working one way.

One solution is to use objects rather than primitives e.g.

<input ng-model="anObject.valueX" />

But it does not work all the time. In the case it doesn't work, another option is to explicitly reference the $parent scope:

<input ng-model="$parent.anObject.valueX" />

Reference: https://github.com/angular/angular.js/wiki/Understanding-Scopes

No comments:

Post a Comment