Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs ng-if is not working for nested ng-if

Tags:

angularjs

In the code below the 2nd checkbox does not work when the 1st checkbox is clicked.

http://plnkr.co/edit/JF0IftvWx7Ew3N43Csji?p=preview

HTML:

<html ng-app="App">
    <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular-animate.min.js"></script>
    <link rel="stylesheet" type="text/css" href="animations.css" />
    <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
         Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/>
         Show when checked:
         <span  ng-if="checked==true" class="animate-if">
             <input type="checkbox" ng-model="checked1" ng-init="checked1=true" />
         </span>
         <br>
         <span  ng-if="checked1==true" class="animate-if">
          test <input type="checkbox" ng-model="checked2" ng-init="checked2=true" />
         </span>
     </body>
</html>
like image 587
Soni Avatar asked Nov 18 '13 11:11

Soni


3 Answers

As noted ng-if creates it's own scope.

You're setting checked1 inside what I'm calling "Inner Scope 1". Then using it in "Outer Scope". "Outer Scope" can't see into "Inner Scope 1" so javascript creates a new variable checked1 on "Outer Scope". Now you have two entirely different variables both calledchecked1- one on "Outer Scope" and one on "Inner Scope1". This is not what you want.

enter image description here

To fix this you need to set checked1 on the same scope as you'll use it- "Outer Scope". "Outer Scope" is the parent of "Inner Scope1" so we can use $parent.checked1 like so:

<input type="checkbox" ng-model="$parent.checked1" ng-init="checked1=true" />

Now there's only one copy of checked1- the one on "Outer Scope". And it works, check it out on this updated plunker: http://plnkr.co/edit/XaPWYvYLrFRZdN2OYn6x?p=preview

like image 103
KayakDave Avatar answered Nov 12 '22 02:11

KayakDave


ngIf creates a different scope. Use $parent:

<span ng-if="checked==true" class="animate-if">
    <input type="checkbox" ng-model="$parent.checked1" 
    ng-init="$parent.checked1=true" />
</span>
<br>
<span ng-if="checked1==true" class="animate-if">
    test <input type="checkbox" ng-model="$parent.checked2" 
    ng-init="$parent.checked2=true" />
</span>

Plunk

like image 29
AlwaysALearner Avatar answered Nov 12 '22 02:11

AlwaysALearner


You can use ngShow instead of ngIf. ngShow helps because it doesn't create child scope. See result here.

like image 1
Vasiliy Kevroletin Avatar answered Nov 12 '22 03:11

Vasiliy Kevroletin