AngularJS - When should I use ng-show and when should I use ng-hide?

2

I'm seeing a tutorial, and at a certain point it shows the code saying that the most correct is to use ng-hide in the DIV tag and below 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>

    
asked by anonymous 02.02.2016 / 15:38

1 answer

7

Very simply:

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

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

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

Case 02: Hide a div when idade value 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 happens for Case 02, but with the inverse logic. The div will always be displayed, however, if the age is less than 18, it will not appear.

Important note

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

In contrast, there is ng-if , it works similarly, see:

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

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

But then, what's the difference?

ng-if will not render div in its html while the value is not "Pedro", that is, it does not exist in its html .

    
02.02.2016 / 16:18