How to use ng-show and ng-hide directives to control visibility of HTML elements

When developing a user input form, lot of time we have to present different options to the user based on their earlier choices. This update to the user interface some time require showing some new input elements or hiding existing elements based on the choice user has just made.

In classical implementation to handle this user interaction, you will end up handling change events on elements and then add or remove display style with value of none or block depending on if you are trying to show or hide.

Show and hide using angular directive

angularJS framework provides directives to handle this very efficiently and in more modular way. There are two directives ng-show and ng-hide available to you. As the names suggest these directives can be applied on HTML elements to control their visibility. These directives allow you to set a predicate that evaluates to an expression that allows ng-show and ng-hide to apply appropriate visibility styles on HTML elements. A typical use of these directives is as shown below.

The following image shows example implementation of view when it has all options available to the user.


<div class="form-group checkbox" ng-hide="fixedPriceListing()">
    <input type="checkbox" ng-model="thisListing.AllowTradeNow" /> Allow trade now

First section shows use of ng-hide directive. The decision making expression on this directive is a behavior function fixedPriceListing. This function checks the value of a property defined in scope's model and returns true or false. As described in angularJS documentation, the return value from the expression or behavior function can be one of the following values.

"f" / "0" / "false" / "no" / "n" / "[]"

 $scope.fixedPriceListing = function() {
   return $scope.thisListing && $scope.thisListing.ListingType == 'FixedPriceOffer';

The effect of this directive can be seen in following snapshot. As soon as user has changed the listing type to FixedPriceOffer, the check box for "Allow trade now" has disappeared.


<div class="form-group col-xs-4" ng-show="thisListing.AllowTradeNow">
    <label>Trade now price</label>
    <input class="form-control" type="number" ng-model="thisListing.Price.TradeNowPrice" 
           placeholder="Trade now price" />

In the above example, ng-show directive has been applied on control visibility of a block displaying a text box. The expression deciding the visibility in this case is a property AllowTradeNow for model's object.

The effect of this implementation of ng-show directive can be seen in following snapshot. As soon as user checks Allow trade now checkbox, user is presented with text box to enter Trade now price. And if user un-checks this check box, the text box will disappear as well.


You can play with these directives in prototype implementation that I have put together. Click here to see this demo user interface

comments powered by Disqus

Blog Tags