I was reading Angular js docs when I came across the issues mentioned related to using ng-model
with directives like ng-include
, ng-switch
, and ng-view
.The reason mentioned was child scope
and parent scope
but I was not able to understand it completely.
Also it was mentioned that issue with primitives can be easily avoided by following the "best practice" of always have a '.' in your ng-model
.
Here's the link
Can anyone please explain it in less-technical language?

- 1,281
- 4
- 18
- 31
-
http://stackoverflow.com/questions/14049480/what-are-the-nuances-of-scope-prototypal-prototypical-inheritance-in-angularjs?rq=1 - best explanation of scopes in Angular. – tymeJV Jan 19 '16 at 14:00
-
Check out egghead video in first answer here http://stackoverflow.com/questions/17606936/angularjs-dot-in-ng-model 3 minutes of enlightenment – charlietfl Jan 19 '16 at 14:16
1 Answers
ng-include
, ng-switch
and ng-if
creates child scope.
It means that if you create
<div ng-controller="MyCtrl">
<div id="innerDiv" ng-if="!something">
<input ng-model="model">
</div>
</div>`
the model
will be created in scope created by the #innerDiv
(because of using ng-if
). It might be problematic if you want to use model
value in the controller, because it won't be possible (Parent scope has no access to properties of child scope!).
The solution is to use $parent.model
in <input ng-model="model">
. Then the property will be changed in parent's scope and that is what you usually want to achieve.
However using $parent
might look not good for someone, so better solution is to create a named model in the controller. The you can use it and follow the rule "always have a '.' in your ng-model." Child scope created by ng-if
has access to parrent scope, so he can use already defined $scope.model
and change $scope.model.text
property.
Controller:
$scope.model = {};
Html:
<div ng-controller="MyCtrl">
<div id="innerDiv" ng-if="!something">
<input ng-model="model.text">
</div>
</div>`
(But remember that if you not define $scope.model
in the controller, it would behave like in first example).
If you are not sure that you are in the same scopes, you can check it by displaying scope's $id
. Simply add in html {{$id}}
above ng-if
(or ng-include
, ng-switch
) and inside.
<div ng-controller="MyCtrl">
scope id: {{$id}}
<div id="innerDiv" ng-if="!something">
child scope id:{{$id}}
</div>
<div>scope id again {{$id}}</div>
</div>`
Some examples: https://jsfiddle.net/La90btfh/3/

- 3,712
- 26
- 43