AngularJS Directive Child Scope – ng-repeat & ng-model

In this blog we will see what is a child scope of a directive and what are its implications.

The Problem

As we know $scope is responsible for a two way data binding between HTML & Data. But in case of a child scope, this two way data bind breaks, lets see with an example how

In the above example, if you any text on parent input it get automatically reflected in the child input. But writing anything in the child input doesn’t translate upwards to the parent input. So this clearly shows the two way data binding breaks in case of child scopes. The reason for this doesn’t lie with angularjs implementation of scope, but rather in how javascript inheritance works. If you wish to go into more detail on this, read this excellence article on this.

How Does This Matter Really

So one could think, why does this problem actually matter. There are many directives and patterns, which force us to use child scope. Directive like ng-repeat, ion-content which create their own child scope, so we need to know how to deal with this problem.

The Solution

Turns out the solution is quite simple, we need to use the (.) operator.
We need to define the data as an object and use that in ng-model

$ = {
        text : ''

more details in the example below

It also considered as a thumb rule to use (.) notation for all your ng-model bindings.