ng-if is detaching input from scope? or I'm just doing something wrong? when using:
<input ng-if="1===1" ng-model="name">
changes in input dont affect the scope. try removing the ng-if and walla! what is that?
attached pluncker
Since ng-if
creates an isolated scope, it won't be able to overwrite properties of it's parent scope. This is how prototypical inheritance works.
While you can use $parent
to dig into the enclosing scope this is a fragile solution that will break if another level is introduced to the hierarchy.
Instead, you should not be putting attributes directly on scope, but instead keep them on an object.
Changes you could make to fix this:
app.controller('MainCtrl', function($scope) {
$scope.model = {
name: 'World'
}
});
and
<body ng-controller="MainCtrl">
<input ng-if="1===1" ng-model="model.name">
<p>Hello {{model.name}}!</p>
</body>
See updated plunk
ng-if
creates a new child scope, thus you're editing the model in the child scope instead of the original one. If you change it to $parent.name
it works just fine.
And here's the reasoning behind it by one of the guys from the Angular team:
The reason why ng-switch creates a new scope, is that scope is used for memory management.
When the switch branch is removed we need to remove all of the bindings as well as all of the click listeners. This is all done through scope.
To put it differently whenever DOM structure changes, a new scope needs to be created, so that we can properly clean up after ourselves.
https://groups.google.com/forum/#!searchin/angular/why$20does$20ng-switch/angular/n_PlBtwemJg/kk6me3JdE88J
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With