Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why ng-if detach from scope?

Tags:

angularjs

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

like image 963
alonn24 Avatar asked Dec 12 '22 04:12

alonn24


2 Answers

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

like image 84
ivarni Avatar answered Dec 21 '22 22:12

ivarni


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

like image 35
Jon Snow Avatar answered Dec 22 '22 00:12

Jon Snow