[angularjs] How to make use of ng-if , ng-else in angularJS

I want to compare id.here if id equals 5 do this, else do that. How can I achieve this?

<div class="case" data-ng-if="data.id === '5' ">
    <input type="checkbox" id="{{data.id}}" value="{{data.displayName}}"
            data-ng-model="customizationCntrl.check[data.id1]"
            data-ng-checked="{{data.status}}=='1'" onclick="return false;">{{data.displayName}}
        <br>
</div>
<div class="case" data-ng-else>
    <input type="checkbox" id="{{data.id}}" value="{{data.displayName}}"
            data-ng-model="customizationCntrl.check[data.id]"
            data-ng-checked="{{data.status}}=='1'">{{data.displayName}}<br>
</div> 

This question is related to angularjs

The answer is


The syntax for ng if else in angular is :

<div class="case" *ngIf="data.id === '5'; else elsepart; ">
    <input type="checkbox" id="{{data.id}}" value="{{data.displayName}}" 
    data-ng-model="customizationCntrl.check[data.id1]" data-ng-checked="
    {{data.status}}=='1'" onclick="return false;">{{data.displayName}}<br>
</div>
<ng-template #elsepart>
    <div class="case">
        <input type="checkbox" id="{{data.id}}" value={{data.displayName}}"  
        data-ng-model="customizationCntrl.check[data.id]" data-ng-checked="
        {{data.status}}=='1'">{{data.displayName}}<br>
    </div> 
</ng-template>

You can write as:

<div class="case" ng-if="mydata.id === '5' ">
    <p> this will execute </p>
</div>
<div class="case" ng-if="mydata.id !== '5' ">
    <p> this will execute </p>
</div> 

There is no directive for ng-else

You can use ng-if to achieve if(){..} else{..} in angularJs.

For your current situation,

<div ng-if="data.id == 5">
<!-- If block -->
</div>
<div ng-if="data.id != 5">
<!-- Your Else Block -->
</div>

You can also try ternary operator. Something like this

{{data.id === 5 ? "it's true" : "it's false"}}

Change your html code little bit and try this hope so it will be work for you.


I am adding some of the important concern about ng directives:-

  1. Directives will respond the same place where it's execute.
  2. ng-else concept is not there, you can with only if, or other flavor like switch statement.

Check out the below example:-

<div ng-if="data.type == 'FirstValue' ">

//different template with hoot data

</div>

<div ng-if="data.type == 'SecondValue' ">

  //different template with story data

</div>

<div ng-if="data.type == 'ThirdValue' ">

 //different template with article data

</div>

As per datatype it is going to render any one of the div.


<span ng-if="verifyName.indicator == 1"><i class="fa fa-check"></i></span>
<span ng-if="verifyName.indicator == 0"><i class="fa fa-times"></i></span>

try this code. here verifyName.indicator value is coming from controller. this works for me.