How to use ngshow and nghide in angularjs

Rakesh Sharma      No Comments  

How to use ngshow and nghide in angularjs with examples

How to use ngshow and nghide in angularjs

ngShow and ngHide known as a directive in angularjs. As per names you can guess it’s uses for show or hide the given HTML element. Today we will explore how to use ngshow and nghide in angularjs.

ngShow – ngShow directive is a part of module ng. ngShow directive shows or hides given html element basis on expression provided to the ng-show attribute.

Usage

<any ng-show="expression"></any>

For more details follow ngShow docs

ngHide – ngHide directive also part of module ng. Also shows or hides given html element basis on expression provided to the ng-hide attribute.

Usage

<any ng-hide="expression"></any>

For more details follow ngHide docs

To use ngShow or ngHide, just add the directive to the element as an attribute you’d like to show or hide.

Working with functions :-

We have added ng-show directive to our html element ng-show="show". Then we are calling two function on different buttons, like ng-click="showMe();" and ng-click="hideMe();" to hide and show elements.
Now what we write of angularjs script for this do.

angular.module('showHideApp',[]).controller('showHideController', function($scope){
  $scope.showMe = function(){
    $scope.show=true;
  }
  $scope.hideMe = function(){
    $scope.show=false;
  }
});

On call showMe() function we are setting $scope.show=true; which will return true and shows the element. And hideMe() function will add false so a nghide css class will be added dynamically to this to hide the element.

Working with Boolean values :-

In this example We creating our link that uses ng-click and will toggle the show variable to true or false.

<button class="btn btn-danger" ng-click="show = !show">

Working with Expressions :-

In this example we are using ng-model which binds elements to a property on the scope. So we will bind our input box to a variable called languages.

<input type="text" class="form-control" ng-model="languages">

Then we are using ng-show to evaluate or compare binded value to show or hide an element. Which compare the variable value and shows result according this.

<div class="form-group" ng-show="languages == 'php'"><p>I am working on PHP </p></div>

There is more ways to use ng-show and ng-hide directive, but i am sharing that simple ways to understanding how to use ngshow and nghide in angularjs.