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>
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.
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
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
You can use ngShow instead of ngIf. ngShow helps because it doesn't create child scope. See result here.
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