Angularjs - When should I use ng-show and when should I use ng-Hide?

Asked

Viewed 8,263 times

3

I am seeing a tutorial, and at a certain point it presents the code saying that the most correct is to use ng-Hide in the DIV tag and further down in the BUTTON tag the same used ng-show. When should I use each of them?

<body ng-controller="StoreController as store">
<div ng-show="!store.product.soldOut">
    <h1> {{store.product.name}} </h1>
    <h2> ${{store.product.price}} </h2>
    <p> {{store.product.description}} </p>
    <button ng-show="store.product.canPurchase">Add to Cart </button>
</div>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>

  • ng-show="!store.product.soldOut" amounts to ng-hide="store.product.soldOut" .

1 answer

10


Quite simply:

  • ng-show: when you want to display content on some condition;
  • ng-hide: when you want to hide content on some condition;

Case 01: Display a div when the value of nome for Pedro

<div ng-show="nome == 'Pedro'"> </div>

Case 02: Hide a div when value of idade is less than 18:

<div ng-hide="idade < 18"> </div>

in Case 01, the div will only be displayed if the name value is "Peter", if it is any other value, whether it is valid or not, it will never be displayed. The same is true for Case 02, but with the reverse logic. A div will always be displayed, however, if the age is less than 18, she nay will be shown.

Important remark

What you should be aware when using ng-show and/or ng-hide is that the div (or any other element using the properties) will still exist in your html. Their effect is to just control the display through the property css display changing display:hidden when you need to exclude.

On the other hand, there is the ng-if, it works in a similar way, see:

<div ng-if="nome == 'Pedro'"></div>

In this case the div will only be displayed if the name value is Pedro.

But then what’s the difference?

The ng-if will not render the div in his html as long as the value is not "Peter", that is, it does not exist in his html.

  • 2

    +1 - Remember that using ng-if objects in the DOM are destroyed/rebuilt, while ng-show and ng-hide only control visibility. Important if reconstruction costs or state guarantee to controllers is a critical point.

  • Well remembered @lbotinelly

Browser other questions tagged

You are not signed in. Login or sign up in order to post.