Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Else if in angular js template [duplicate]

I need to use else if in angularjs template .What is the syntax ? For example in c i would write the code like below:

if (data.sender=='system')
{data.receiver}
else if (data.sender=='mail')
{data.receiver} 
else {data.sender}

My code:

{{data.sender == 'System' ? data.receiver : ' '}}

{{data.sender =='mail' ? data.receiver : data.sender  }}
like image 838
query Avatar asked Jan 01 '15 16:01

query


3 Answers

{{(data.sender === 'system' || data.sender === 'mail') ? data.receiver : data.sender}}
like image 79
hjl Avatar answered Nov 20 '22 18:11

hjl


There are no if-else syntax in angular templates as you are looking for. Too much logic in the templates makes it difficult to maintain. Here are two possible solutions:

<span ng-show="data.sender == 'mail' || data.sender=='system'">{{data.receiver}}</span>
<span ng-show="data.sender != 'mail' && data.sender!='system'">{{data.sender}}</span>

You can also use ng-switch in a similar way:

<span ng-switch="data.sender">
    <span ng-switch-when="mail">{{data.receiver}}</span>
    <span ng-switch-when="system">{{data.receiver}}</span>
    <span ng-switch-default>{{data.sender}}</span>
</span>

The later having the advantage that only one of the spans will exist in the document where ng-show/ng-hide all spans exist in the document they are just hidden using display:none.

Other options would be writing your own directive, or creating special filters.

like image 8
chubbsondubs Avatar answered Nov 20 '22 18:11

chubbsondubs


Here it is, but you should really try to avoid having this kind of complicated logic inside of templates, as a rule of thumb.

{{ data.sender == 'system' ? data.receiver : data.sender == 'mail' ? data.receiver : data.sender }}
like image 2
holographic-principle Avatar answered Nov 20 '22 18:11

holographic-principle