AngularJS ng-if and scopes

be-codified picture be-codified · Jun 11, 2015 · Viewed 33.7k times · Source

I am trying to understand ng-if and scopes. As I am aware, ng-if creates a new child scope. Here is my issue:

View

<input ng-model="someValue1" />
<div ng-if="!someCondition">
    <input ng-model="$parent.someValue2" />
</div>

Controller

$scope.someCondition = true;

if ($scope.someCondition) {
    $scope.someValue2 = $scope.someValue1;        
}

If someCondition is set to true, then someValue2 should be the same as someValue1.

My problem is that I can't access someValue2 in both situations (true or false). How could I achieve this?

Answer

Ankur Soni picture Ankur Soni · Mar 30, 2016

Yes, ng-if creates a new child scope

To watch a model property in an ng-if, the rule-of-thumb is:

DO NOT USE THE SCOPE AS MODEL

e.g.

ng-if='showStuff' //here my scope is model **INCORRECT**
ng-if='someObject.showStuff' // ** CORRECT **

Use an object property in ng-model - then, even if ng-if creates the new child scope, the parent scope will have the changes.

To see a working Plunker, look here : http://jsfiddle.net/Erk4V/4/