EDUCBA Logo

EDUCBA

MENUMENU
  • Explore
    • EDUCBA Pro
    • PRO Bundles
    • Featured Skills
    • New & Trending
    • Fresh Entries
    • Finance
    • Data Science
    • Programming and Dev
    • Excel
    • Marketing
    • HR
    • PDP
    • VFX and Design
    • Project Management
    • Exam Prep
    • All Courses
  • Blog
  • Enterprise
  • Free Courses
  • Log in
  • Sign Up
Home Software Development Software Development Tutorials AngularJS Tutorial AngularJS ng-if
 

AngularJS ng-if

Kinjal Lodha
Article byKinjal Lodha
EDUCBA
Reviewed byRavi Rathore

Updated April 12, 2023

AngularJS ng-if

 

 

Definition of AngularJS ng-if

AngularJS ng-if is an In-Built AngularJS directive which can be used on HTML view Page to remove or add a particular section to the HTML view based on evaluation of expression defined in ng-if. As the name says, if the expression assigned to ng-if directive evaluates to TRUE Boolean value then that element gets added to the HTML view, else it is removed completely from the DOM itself.

Watch our Demo Courses and Videos

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

Syntax

Using with INPUT Element

<input type="email" ng-if="isValidEmail()"
ng-model="emailValue" placeholder="Enter Email id"/>

Using with SELECT Element

<select ng-model="selectedSubject" ng-if="showDropdown()"
ng-options="subject as subject.value for subject in subjects">
<option value="" selected>Select a Subject</option>
</select>

Using with DIV Element

<div ng-if="showDivPortion()" ng-model="textAreaValue">This section will be displayed only if ng-if is evaluated to TRUE</div>

Along with these ng-if directive can also be used with input type email, tel, checkbox, radio buttons, name, and all types of HTML tags.

How AngularJS ng-if works?

In AngularJS framework, it is very important to know that all the In-Built directive which have been provisioned by AngularJS framework will always be denoted with ng prefix. The expression defined in ng-if directive evaluates to a Boolean value i.e. True or False and based on this value the element is displayed on HTML DOM. Whenever the ng-if expression evaluation is a False value then that element is removed from the DOM itself. One very important difference between ng-if and ng-show directive is that, when expression evaluation of ng-if directive is FALSE, then the element is removed from the DOM itself whereas in case of ng-show, when expression return FALSE value then the element is hided in the DOM and not removed which is done using CSS property of display hidden.

Another point to keep a note is that when an HTML element is removed using ngIf its scope is completely destroyed and a new scope is created when the element is restored back in the view. The scope is inherits from ng-if’s parent scope. AngularJS ng-if directives is executed at priority level 600 and can be executed as multiElement.

Examples

Let us discuss examples of AngularJS ng-if.

Example #1

Index.html

<html ng-app="subjectapp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="script.js"></script>
<style>
.subject-dropdown {
width: 80%;
height: 35px;
line-height: 35px;
color: primary-blue;
border: 1px solid primary-blue;
margin-left: 40px;
}
.text-msg {
margin-top: 20px;
font-weight: bold;
text-align:center;
color: red;
}
</style>
</head>
<body>
<div ng-controller='SubjectController'>
<select class="subject-dropdown" ng-model="selectedSubject"
ng-if="onChangeOfSubjects()"
ng-options="subject as subject.value for subject in subjects">
<option value="" selected>Select a Subject</option>
</select>
<div class="text-msg" ng-if="selectedSubject">The subject selected is {{subjectValue}}
and subject Code is {{subjectCode}}
</div>
</div>
</body>
</html>

Script.js

angular.module('subjectapp', [])
.controller('SubjectController', function($scope) {
$scope.subjects = [{'key': '01', 'value': 'English'},
{'key': '02', 'value': 'History'},
{'key': '03', 'value': 'Mathematics'},
{'key': '04', 'value': 'Science'},
{'key': '05', 'value': 'French'}];
$scope.onChangeOfSubjects = onChangeOfSubjects;
function onChangeOfSubjects() {
$scope.subjectValue = $scope.selectedSubject.value;
$scope.subjectCode = $scope.selectedSubject.key;
}
});

In above example, we are trying to display a list of Subjects on UI using a select tag so that it will display in dropdown with various subjects available. To the select HTML tag, we have added ng-if directive, so as soon as the dropdown value is changed from its current ng-model value then ng-if will get triggered. This ng-if will execute function onChangeOfSubjects which is defined in the corresponding controller. Also as Subject is an object of key-value pair, we are displaying the name of the selected subject and its corresponding Subject code. Make sure to include the AngularJS dependency in Script tag so that you will be able to use the ng-repeat directive of AngularJS.

ng-if="onChangeOfSubjects()"

Here onChangeOfSubjects method will get executed, whenever ng-if is triggered. It can accept any number of parameter and we are not passing any as we will be using scope model value in controller.

ng-model="selectedSubject"

As discussed above, ng-if can work only with ng-model in this and so we have used ng-model in select

Just by using a few simple and easy CSS styling, we will be able to view the output of the above code.

Output:

AngularJS ng-if 1

AngularJS ng-if 2

Example #2

Index.html

<html ng-app="emailapp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="script.js"></script>
<style>
.email-input {
width: 80%;
height: 35px;
line-height: 35px;
color: primary-blue;
border: 1px solid primary-blue;
margin-left: 40px;
}
.text-msg {
margin-top: 20px;
font-weight: bold;
text-align:center;
color: Blue;
}
</style>
</head>
<body>
<div ng-controller='EmailController'>
<input class="email-input" type="email"
ng-if="onChangeOfEmail()"
ng-model="emailValue" placeholder="Enter Email id"/>
<p class="text-msg" ng-if="emailValue">Email id {{emailValue}} is {{validityValue}}</p>
</div>
</body>
</html>

Script.js

angular.module('emailapp', [])
.controller('EmailController', function($scope) {
$scope.onChangeOfEmail = onChangeOfEmail;
function onChangeOfEmail() {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
$scope.validityValue = re.test($scope.emailValue) ? 'Valid' : 'Invalid';
}
});

In above example, we are trying to accept input as Email id on UI using INPUT tag so that it will display the email id. To the input HTML tag, we have added ng-if directive, so as soon as the email id is entered or changed from its current ng-model value then ng-if will get triggered. This ng-if will execute function onChangeOfEmail which is defined in the corresponding controller. In this controller method, we will validate whether the email id is a valid email id based on pattern defined. If it’s valid we assign scope variable value as valid and if invalid, invalid string is assigned to validityValue. Make sure to include the AngularJS dependency in Script tag so that you will be able to use the ng-repeat directive of AngularJS.

ng-if=" onChangeOfEmail ()"

Here onChangeOfEmail method will get executed, whenever ng-if is triggered. This method will be checking for whether it’s a valid email id or not.

ng-model=" emailValue "

As discussed above, ng-if can work only with ng-model in this and so we have used ng-model in select

Just by using a few simple and easy CSS styling, we will be able to view the output of the above code.

Output:

 AngularJS ng-if 3

example 2

Conclusion

ng-if directive in AngularJS is another most widely preferred and useful In-Built AngularJS directive which can be used for conditionally modifying the elements in HTML view. Knowing the syntax is all that is needed and you are ready to go.

Recommended Articles

We hope that this EDUCBA information on “AngularJS ng-if” was beneficial to you. You can view EDUCBA’s recommended articles for more information.

  1. AngularJS Number Filter
  2. AngularJS Date Filter
  3. AngularJS ng-class
  4. AngularJS ng-disabled

Primary Sidebar

Footer

Follow us!
  • EDUCBA FacebookEDUCBA TwitterEDUCBA LinkedINEDUCBA Instagram
  • EDUCBA YoutubeEDUCBA CourseraEDUCBA Udemy
APPS
EDUCBA Android AppEDUCBA iOS App
Blog
  • Blog
  • Free Tutorials
  • About us
  • Contact us
  • Log in
Courses
  • Enterprise Solutions
  • Free Courses
  • Explore Programs
  • All Courses
  • All in One Bundles
  • Sign up
Email
  • [email protected]

ISO 10004:2018 & ISO 9001:2015 Certified

© 2025 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

EDUCBA Login

Forgot Password?

🚀 Limited Time Offer! - 🎁 ENROLL NOW