ng-Show And ng-Hide Directive In AngularJS

In a real time development scenario, we are getting the client side requirement to hide/show a particular control , based on the condition. When we work in jQuery, we have .show and .hide. Now, everyone is talking about Angularjs. Thus, in this article, I am going to show you, how you can show or hide a particular control.

In this tutorial, I am taking a small example. We have one Check box and an image. If Check box is checked, an image will be shown, if checkbox is unchecked, image will hide.

To use Angular in your application, right click on the Solution and select Manage NuGet.

application

Now, you will get dialog box for NuGet.

dialog box

Now, select AngularJS Core and click Install. Your Angularjs file will load into your solution.

Now, add <script src="Scripts/angular.min.js"></script> in your HTML file.

Thus, let's start with ng-show.

  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2.   
  3. <head>  
  4.     <title></title>  
  5.     <script src="Scripts/angular.min.js"></script>  
  6. </head>  
  7.   
  8. <body ng-app> <br /><br /><br /><br /> <label>Hide/Show</label> <input type="checkbox" ng-model="showImage" /> <br /><br /><br /><br /> <img src="images/Angularjs.png" ng-show="showImage" /> </body>  
  9.   
  10. </html>  
If you run the code, mentioned above, you will get the output, mentioned below:

output

If Checkbox is checked, you can see the image. Now, the question arises, how does ng-show work.

As you see, we have Checkbox. Here, we use ng-model. Thus, if showImage = true, ng-show value is going to be true. If it is false, ng-show works as false.

In the example, mentioned above, if we want to use ng-hide, see the code, given below:
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3.   
  4. <head>  
  5.     <title></title>  
  6.     <script src="Scripts/angular.min.js"></script>  
  7. </head>  
  8.   
  9. <body ng-app> <br /><br /><br /><br /> <label>Hide/Show</label> <input type="checkbox" ng-model="showImage" /> <br /><br /><br /><br /> <img src="images/Angularjs.png" ng-hide="!showImage" /> </body>  
  10.   
  11. </html>  
ng-hide will hide the image, if showImage value is false and if the value is true, you can see the image.

Definations

 

  1. Ng-model - The ng-model directive binds the value of HTML controls (input, select, textarea) to the Application data.
  2. Ng-hide - The ng-hide directive hides the HTML element, if the expression evaluates to true.
  3. Ng-show- The ng-show directive shows the specified HTML element, if the expression evaluates to true, else HTML element is hidden.