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

匿名 (未验证) 提交于 2019-12-03 03:04:01

问题:

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>  

回答1:

Use ng-switch with expression and ng-switch-when for matching expression value:

<div ng-switch="data.id">   <div ng-switch-when="5">...</div>   <div ng-switch-default>...</div> </div> 

Example is here

Angular2 example



回答2:

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> 


回答3:

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.



回答4:

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.



回答5:

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> 


回答6:

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>  


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!