In this article I will explain with an example, how to show an element using ng-show directive when the Variable (Model) is not NULL and if the Variable (Model) is NULL or empty then the element must be hidden using AngularJS.
The AngularJS ng-show directive will be assigned a condition where the Variable (Model) will be tested for NULL and if the Variable (Model) is not NULL, the condition will return True, thus the element will be shown else vice-versa.
Showing using ng-show if Variable (Model) not NULL using AngularJS
The below HTML Markup consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
The HTML markup consists of an HTML DIV and a CheckBox. The HTML DIV has been assigned ng-show directive. The value of ng-show directive has been set using a condition where the variable IsVisible is checked against NULL and hence the HTML DIV is hidden when page loads.
The CheckBox has been assigned ng-change directive. When the CheckBox is clicked i.e. checked – unchecked or selected – unselected, the ShowHide function of the Controller gets called.
Inside the function, the value of the IsVisible variable is set to True if the CheckBox is checked and NULL if the CheckBox is unchecked.
This makes the HTML DIV toggle when the CheckBox is clicked i.e. checked – unchecked or selected – unselected.
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope) {
//This will hide the DIV by default.
$scope.IsVisible = null;
$scope.ShowHide = function () {
//If DIV is visible it will be hidden and vice versa.
$scope.IsVisible = $scope.ShowPassport ? true : null;
}
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
<label for="chkPassport">
<input type="checkbox" id="chkPassport" ng-model="ShowPassport" ng-change="ShowHide()" />
Do you have Passport?
</label>
<hr />
<div ng-show="IsVisible != null">
Passport Number:
<input type="text" id="txtPassportNumber" />
</div>
</div>
</body>
</html>
Screenshot
Demo
Downloads