AngularJS

Angular – conditional statements

You all might be familiar with conditional statements which are if, if-else and switch in various programming languages like JavaScript, java, c++, etc.
I am here to tell how you can use the same conditional statements here in angular.

  1. If statement : To get the same result as if statement, angular provides a directive which is ng-if, it relies upon evaluating an expression as true or false. In the case of ng-if, if the expression evaluates false, it removes the element from the DOM entirely, if it’s true, the element gets recreated. Syntax is as follows:
    <element ng-if="expression"></element>
    In the example below I am using ng-if="time >=4 && time < 12" to display div with message  Good Morning!
  2. If-else statement : Well angular does not provide a else directive so to achieve the result of if-else you can use ng-if one with positive expression and other with negation of expression.
    Syntax is as follows:
    <element ng-if="expression1"></element>
    <element
     ng-if=”!expression1″></element>
    In the example below I am using ng-if="time >=4 && time < 12" to display div with message  Good Morning!  and for else I am using not of above condition as ng-if="!(time >=4 && time < 12)" to display div with message So sad, You missed morning
  3. Switch statement : Just as you use switch statement angular provides similar directive ng-switch. The ng-switch-when directive informs the parent ng-switch of which view to display when the expression is evaluated. When no matching expression is found on a ng-switch-when view, the ng-switch-default view is stamped out.
    Syntax is as follows:
    <element ng-switch="expression">
    <element ng-switch-when="value"></element>
    <element ng-switch-when="value"></element>
    <element ng-switch-when="value"></element>
    <element ng-switch-default></element>
    </element>
    In the example below I am using switch statement to display 3 different div with their messages and in the default I am having a div with message You entered wrong number try to enter 1, 2 or 3.

Let me know your thoughts