angularjs – 如果父项具有ng-if,则Angular ng-show不起作用

我有一个视图,其中父div具有ng-if,并且一些子元素具有ng-show.当嵌套在具有ng-if的元素下时,ng-show似乎无法正常工作.这是一个Angular bug还是我做错了什么? 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:

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

谢谢,

安迪

与ng-show不同,ng-if指令创建一个新范围.

因此,如果在子范围内而不是在主范围上设置showIt属性,则在ng内部编写showIt = true.

要修复它,请使用$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>

演示Plunker.

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...