Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / .NET

ng-show and ng-hide Directives in AngularJs

4.38/5 (5 votes)
16 Aug 2016CPOL1 min read 9.8K  
ng-show and ng-hide directives in AngularJs

Introduction

In the 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 how you can show or hide a particular control.

Using the Code

In this tutorial, I am taking a small example. We have one checkbox and an image. If checkbox 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.

Image 1

Now, you will get dialog box for NuGet.

Image 2

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.

HTML
<html> 
<head>
<title></title> 
 <script src="Scripts/angular.min.js"></script>
</head>  
<body ng-app>  
<label>Hide/Show</label> <input type="checkbox" ng-model="showImage" />  
<img src="images/Angularjs.png" ng-show="showImage" /> </body>  
</html>

If you run the code mentioned above, you will get the output mentioned below:

Image 3

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

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:

HTML
<html> 
<head>
<title></title> 
 <script src="Scripts/angular.min.js"></script>
</head>  
<body ng-app>  
<label>Hide/Show</label> <input type="checkbox" ng-model="showImage" />  
<img src="images/Angularjs.png" ng-hide="!showImage" /> </body> 
</html>

ng-hide will hide the image, if showImage value is false and if the value is true, you can see the image.

Definitions

  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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)