if else statement in AngularJS templates.
If else statement in AngularJS.
14917-Jun-2024
Updated on 18-Jun-2024
Home / DeveloperSection / Forums / If else statement in AngularJS.
if else statement in AngularJS templates.
Ashutosh Kumar Verma
18-Jun-2024If-else in AngularJS
In AngularJS, you typically use directives like ng-if, ng-show, and ng-switch to create condition statements directly in your HTML templates, rather than using traditional JavaScript if-else statements
Using ng-if
Removes or reconstructs a portion of the DOM tree based on the
ng-if
specification. It is often used to represent different things in a situation.Using ng-show
ng-show
Conditionally shows or hides objects based on the expression by removing them from the DOM.Using ng-switch
ng-switch
uses conditions to change the DOM structure based on the value.Using JavaScript if-else in AngularJS
AngularJS does not encourage the insertion of JavaScript if-else statements directly into templates for arguments. Instead, you need to prepare the necessary data or boolean expressions in your controller or component, and use the Angular instructions shown above to implement the conditional definition.
Example-
A simple AngularJS program shows how to use of
ng-if
directives.In the example above
A variable
IsLogin
created within the controller and assigned a default valuefalse
.Login()
called when button is clicked that changes the value ofIsLogin
variable.data-ng-if
checks the value ofIsLogin
, if the value is true then that HTML element is visible otherwise hide.Also, Read: How to set focus on input field in AngularJS?