2

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?

1
  • 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
    Jul 27, 2017 at 22:50

3 Answers 3

4

Readability.

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

2

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

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>
2
  • 1
    Would you please provide an example snippet explaining this use case?
    – mattjegan
    Jul 27, 2017 at 23:56
  • 1
    Added an example.
    – hayzey
    Jul 28, 2017 at 0:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.