AngularJS ng-if Directive Example

  Total Views : 1226
  Comments : 0
 
  Keywords : What is ng-if directive in angularjs, ng-if expression example in angularjs, Understand ngif directive in angularjs with example, Angularjs ngif directive documentation with example

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

AngularJS ng-if Directive

The “ng-if” directive in AngularJs is used to remove and reinsert portion HTML DOM element into a 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” completely remove and recreate the HTML portion from the HTML DOM tree.

Syntax of AngularJS ng-if Directive

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.

Example of ng-if Directive in AngularJS

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 ng-if Directive in AngularJS

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.

 Comments (0)

Be the first to give your valuable feedback

Leave a comment

  • Default Tutlane User