AngularJS: Two way data binding fails if element has ngModel and a directive with a local scope

The problem is shown here: http://jsfiddle.net/ews7S/

<input type="text" ng-model="testModel" dir="123">

When an element is bound to a model in a controller scope and you also add a directive to the element that has it's own local scope, then changes to the model only change in the directives scope.

An alternative solution is to use an object for the model, rather than a primitive. Then the new directive scope will inherit (prototypically) a reference to the object, rather than a copy of the primitive's value:

$scope.model = { testProp: "444" };

<input type="text" ng-model="model.testProp" dir="123">
<input type="text" ng-model="model.testProp">

document.getElementById("out").innerHTML = scope.model.testProp;

http://jsfiddle.net/mrajcok/awfU5/

With a primitive, such as $scope.testModel, the directive scope's testModel property gets a copy of the parent scope's testModel's value. Changes to one do not affect the other.

With an object, such as $scope.model, both the parent scope and the directive scope have a reference to the same (one) object. Changes in either affect the same object.

Another (fragile) solution is to use the undocumented $parent property (make these changes to the question fiddle):

<input type="text" ng-model="$parent.testModel" dir="123">

document.getElementById("out").innerHTML = scope.$parent.testModel;

Note that using $parent is a fragile solution because use of $parent depends on the DOM structure. E.g., If another controller was added (explicitly by you, or implicitly by another Angular directive) between the parent and the child (now grandchild), we would then need to use $parent.$parent.testModel.

The solution is to add this to the directive:

scope: {testModel: '=ngModel'},

See here: http://jsfiddle.net/ews7S/1/

Why this works is because the '=' sets up bi-directional binding between a local scope property and the parent scope property (see docs: http://docs.angularjs.org/guide/directive under Directive Definition Object).