如果父级具有ng-if,则角度ng-show无法正常工作 [英] Angular ng-show not working if parent has ng-if

查看:69
本文介绍了如果父级具有ng-if,则角度ng-show无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个视图,其中父div上具有ng-if,而某些子元素上具有ng-show.嵌套在带有ng-if的元素下时,ng-show似乎无法正常工作.这是Angular错误还是我做错了什么? 看到这个小矮人.

I have a view where a parent div has ng-if on it, and some child element has ng-show on it. It seems that the ng-show isn't working correctly when nested under an element with ng-if on it. Is this an Angular bug or am I doing something wrong? See this plunker.

HTML:

<!-- with ng-if on the parent div, the toggle doesn't work -->
    <div ng-if="true">
      <div>
          visibility variable: {{showIt}}
      </div>
      <div ng-show="!showIt">
          <a href="" ng-click="showIt = true">Show It</a>
      </div>
      <div ng-show="showIt">
        This is a dynamically-shown div.
        <a href="" ng-click="hideIt()">Hide it</a>
      </div>
    </div>

    <br/><br/>

    <!-- with ng-show on the parent div, it works -->
    <div ng-show="true">
      <div>
          visibility variable: {{showIt}}
      </div>
      <div ng-show="!showIt">
          <a href="" ng-click="showIt = true">Show It</a>
      </div>
      <div ng-show="showIt">
        This is a dynamically-shown div.
        <a href="" ng-click="hideIt()">Hide it</a>
      </div>
    </div>

JavaScript:

The JavaScript:

scope.hideIt = function () {
  scope.showIt = false;
};

谢谢

安迪

推荐答案

ng-show ng-if指令创建新作用域不同.

因此,当您在ng-if内写入showIt = true时,将在子作用域而不是主作用域上设置showIt属性.

So when you write showIt = true inside the ng-if you are setting the showIt property on your child scope and not on your main scope.

要解决此问题,请使用$parent来访问父级范围内的属性:

To fix it use the $parent to access your property on your parent scope:

<div ng-if="true">
   <div>
       visibility variable: {{showIt}}
   </div>
   <div ng-show="!showIt">
       <a href="" ng-click="$parent.showIt = true">Show It</a>
   </div>
   <div ng-show="showIt">
     This is a dynamically-shown div.
     <a href="" ng-click="hideIt()">Hide it</a>
   </div>
 </div>

演示柱塞.

这篇关于如果父级具有ng-if,则角度ng-show无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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