In this tutorial we will see, how we can use AngularJS ng-show and ng-hide Directives to show and hide the elements.
ng-show
The ng-show directive shows the specified HTML element if the expression evaluates to true, otherwise the HTML element is hidden.
The ng-show directive shows or hides the given HTML element based on the expression provided to the ng-show attribute.
ng-hide
The ng-Hide directive shows or hides the given HTML element based on the expression provided to the ng-Hide attribute.
The ng-Hide directive hides the HTML element if the expression evaluates to true.
ng-Hide is also a predefined CSS class in AngularJS, and sets the element’s display to none.
<!-- ng-show syntax -->
<element ng-show="expression"> </element>
<!-- ======================================= -->
<!-- ng-hide syntax -->
<element ng-hide="expression"> </element>
<!-- When used as a CSS class: -->
<element class="ng-hide"> </element>
Usage
To work with either ngShow or ngHide, just add the directive to the element which you like to show or hide.
<!-- BOOLEAN VALUES =============================== -->
<!-- True Values -->
<div ng-show="sad">this is a emotional quote</div>
<!-- can also show if a value is false -->
<div ng-show="!sad">this is a funny quote</div>
<!-- Where !sad means : not sad-->
<!-- FOR EXPRESSIONS =============================== -->
<!-- show if the appState variable is a string of emotional -->
<div ng-show="appState == 'emotional'">this is a emotional quote</div>
<!-- FOR FUNCTIONS =============================== -->
<!-- use a function defined in your controller to evaluate if true or false -->
<div ng-hide="checkSomething()"></div>
Once we have that set in our markup, we can set the sad or emotional variables different number ways.
Exapmle
Lets us see some examples and demo related to the AngularJS directives i.e ng-show & ng-hide
let’s first set up the angular dependencies and the markup page.
<html>
<head>
<style src="style.css" > </style>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.js"></script>
<script> var app = angular.module('myApp', ['ngAnimate']); </script>
</head>
<body ng-app="myApp">
<h1>Hide the DIV: <input type="checkbox" ng-model="myCheck"></h1>
<div class="msg" ng-hide="myCheck"> If You Click I Will Be Hiding. </div>
</body>
</html>
Putting some style to see the working of the angular directives !
div {
transition: all linear 0.5s;
background-color: #5fc8e8;
height: 100px;
width: 100%;
position: relative;
top: 0;
left: 0;
}
.ng-hide {
height: 0;
width: 0;
background-color: transparent;
top:-200px;
left: 200px;
}
.msg{
font-size:2em;
text-align:center;
padding:3%;
}