2
votes

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?

3
I'd say it's just different preference - sometimes you want to hide an element only in a specific scenario, other times, you want to show it only in specific circumstances. - Yatin

3 Answers

4
votes

Readability.

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

2
votes

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

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>