Justin Carlson Justin Carlson - 1 year ago 104
AngularJS Question

Angularjs ng-model doesn't work inside ng-if

Here is the fiddle showing the problem. http://jsfiddle.net/Erk4V/1/

It appears if I have an ng-model inside of an ng-if, the model does not work as expected.

I am wondering if this is a bug or if I am misunderstanding the proper usage.

<div ng-app >
<div ng-controller="main">

Test A: {{testa}}<br />
Test B: {{testb}}<br />
Test C: {{testc}}<br />

testa (without ng-if): <input type="checkbox" ng-model="testa" />
<div ng-if="!testa">
testb (with ng-if): <input type="checkbox" ng-model="testb" />
<div ng-if="!someothervar">
testc (with ng-if): <input type="checkbox" ng-model="testc" />


Answer Source

The ng-if directive, like other directives creates a child scope. See this fiddle: http://jsfiddle.net/Erk4V/4/

So, your checkbox changes the testb inside of the child scope, but not the outer parent scope.

Note, that if you want to modify the data in the parent scope, you'll need to modify the internal properties of an object like in the last div that I added.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download