Ritesh Puri
Ritesh Puri

Reputation: 327

ng-show and ng-hide usage in AngularJS

I am aware of the difference between ng-show and ng-hide but I was asked a question in an interview that why do we need ng-hide if we have ng-show because we know that both shows or hides the given HTML element based on their values which can be true or false. What is the reason that we should favor ng-show over ng-hide or vice versa?

Upvotes: 2

Views: 1568

Answers (3)

hayzey
hayzey

Reputation: 464

ng-hide takes priority over ng-show. So if you wanted to, you could combine the two and provide them with two different conditions, if you wanted to override ng-show with ng-hide for whatever reason. I would personally advise against this though, as you can just provide multiple conditions to the one directive to achieve what you need.

Example:

<h1>Good dogs</h1>
<div ng-repeat="dog in $ctrl.getDogs()" ng-show="dog.isGoodBoy()" ng-hide="dog.isBadBoy()">
    <p>{{dog.name}} is a good boy.</p>
</div>

Upvotes: 2

w-robot
w-robot

Reputation: 91

One thing to notice is that ng-show and ng-hide doesnt remove or create DOM elements but they simply toggles them being displayed or not with css

So it's easy to toggle one element keeping the other one hidden in the DOM and of course they offer readability as said before.

<p ng-show="guess === number">Correct</p>
<p ng-hide="guess === number">Incorrect</p>

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691715

Readability.

ng-show="feature.enabled" is more readable than ng-hide="!feature.enabled". Double negations are harder to understand.

Upvotes: 4

Related Questions