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--


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="">



AngularJs ng-if Directive Example


<script src=""></script>


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

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

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

$scope.selectval = "one";




<body ng-app="AngularngifApp">

<div ng-controller="ngifctrl">

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


<br /><br />

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

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





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.