一尘不染

如果父级具有ng-if,则角度ng-show不起作用

angularjs

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

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:

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

谢谢,

安迪


阅读 257

收藏
2020-07-04

共1个答案

一尘不染

与指令不同ng-show,它 创建了一个新的作用域*ng-if *

因此,当您showIt = true在内部编写内容时,ng-if您是showIt在子范围而非主范围上设置属性。

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

<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>

演示柱塞

2020-07-04