Gaurav Aggarwal Gaurav Aggarwal - 3 months ago 9
Javascript Question

why use ng-hide when ng-show can work for both situations

I have gone through so many questions like this but got this only solutions that

ng-show
by default hides the element and show it if condition is true and on the other hand
ng-hide
by default show the element and hide it when condition is true.

But my concern is the condition can be taken care of with
ng-show
or
ng-hide
only then why we use different things.

For example

I saw this somewhere in this code user is using
ng-show
and
ng-hide
both

<div ng-init="isShow = 'one'">
<a href="#" ng-click="isShow == 'one' ? isShow = 'two' : isShow = 'one'">
<div ng-show="isShow=='one'">
If One show this
</div>
<div ng-hide="isShow=='one'">
If Two show this
</div>
</div>


But according to me this can be achieved also with this code

<div ng-init="isShow = 'one'">
<a href="#" ng-click="isShow == 'one' ? isShow = 'two' : isShow = 'one'">
<div ng-show="isShow=='one'">
If One show this
</div>
<div ng-show="isShow=='two'">
If Two show this
</div>
</div>


So what exactly is the difference between both the codes. There must be some specific difference if
ng-show
and
ng-hide
both exists. Anyone know it?

Thanks in advance!

Answer

I don't see any reason for this question to be downvoted - it's a valid thought. The reason is simple, though. AngularJS has "declarative" as one of its core philosophies. If 90% of the time you want an element shown, but occasionally it should be hidden, ng-hide="thatcondition" clearly indicates when it should be hdiden. If most of the time it should be HIDDEN, then ng-show="thatrarecondition" is more readable.

Clear, readable code is an important principle in any framework, and especially in AngularJS. The ! operator is narrow and easily missed, far more than any of the other comparisons like >, <, >=, <=, etc. Providing positive- and negative-visibility operators makes it much more readable what's going on here.

An important detail to note is that both directives look for "truthy" values, not exactly-equal ones. JS is pretty vague about this, and sometimes that's an advantage. For example, suppose you have an object that may have a sub-object (a detail element). You might have the detail-display DIV written as follows:

<div ng-show="{{ object.details }}">
    <!-- Render object.details here -->
</div>

This "truthy" comparison is also handy for the negative case. Suppose you want to HIDE an order-cancellation block in a sales system if the order has been shipped. Consider:

<div ng-hide="{{ order.shipped }}">
   Want to cancel this order? <a href="...">click here</a>
</div>

Why is this important? Well, it means ANY non-undefined/null value for order.shipped will hide this block! That means if today, you set it as a true/false, it will work. But tomorrow you change it to a DATE that the order was shipped? The rule will still work! This makes it easy to code (and maintain) displays like this.