Andy Andy - 28 days ago 10
AngularJS Question

Angular ng-show not working if parent has ng-if

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.

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


The JavaScript:

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


Thanks,

Andy

Answer Source

Unlike ng-show the ng-if directive creates a new scope.

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.

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>

Demo Plunker.