AngularJS ng-if Directive Example

Here we will learn ng-if directive in angularjs with an example, use of ng-if directive in angularjs and how to use the ng-if directive in angularjs application with example.

AngularJS ng-if Directive

In angularjs, the ng-if directive is used to remove and reinsert a portion of the HTML DOM element into an HTML template tree. This is executed based on the value of expression assigned to the ng-if attribute.

 

Now the question is what is the difference between ng-if and “ng-show/ng-hide” since they all do the same thing on the browser. Well, the difference is the “ng-show/ng-hide” just do the display and hide of the HTML element by manipulation the display property of the CSS whereas the ng-if directive will remove and recreate the HTML portion from the HTML DOM tree.

AngularJS ng-if Directive Syntax

Following is the syntax of using ng-if directive in angularjs application

 

<div ng-if="youexpression">

 --your code--

</div>

Now we will see how to use ng-if directive in angularjs application with simple example.

AngularJS ng-if Directive Example

Following is the example of using ng-if directive in angularjs application.

 

Live Preview

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>

AngularJs ng-if Directive Example

</title>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<script>

var app = angular.module("AngularngifApp", []);

app.controller("ngifctrl", function ($scope) {

$scope.items = ['one', 'two', 'three', 'four'];

$scope.selectval = "one";

});

</script>

</head>

<body ng-app="AngularngifApp">

<div ng-controller="ngifctrl">

Select Item: <select ng-model="selectval" ng-options="item for item in items">

</select>

<br /><br />

<div ng-if="selectval=='one'" style="border:1px solid #000; padding:10px; width:20%">

<b>Show Div If Selected Value One</b>

</div>

</div>

</body>

</html>

If you observe above code we are showing div if selected value is one otherwise we are hiding div using ng-if directive in angularjs application. Now we will run above code and will see output that would be like as shown below.

Output of AngularJS ng-if Example

Following is the result of using ng-if directive in angularjs applications.

 

Angularjs ng-if directive example output or result

 

This is how we can use ng-if directive or condition in angularjs application.