AngularJs ng-if 不适用于嵌套的 ng-if [英] AngularJs ng-if is not working for nested ng-if

查看:24
本文介绍了AngularJs ng-if 不适用于嵌套的 ng-if的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,当单击第一个复选框时,第二个复选框不起作用.

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

这篇关于AngularJs ng-if 不适用于嵌套的 ng-if的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆