Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add condition to angular expression? [duplicate]

If I have an angular expression which resolves to a String, can I add a condition to that expression which will append extra text to that String?

I have:

<span>{{groupType}}</span>

But if groupType resolves to car or animal, I want to add an s to the end of the String.

Can I add a condition to the expression to accomplish this?

like image 621
Daft Avatar asked Sep 11 '26 00:09

Daft


2 Answers

You can use Ternary operator in Angular expression

<span>{{groupType === 'Car' || groupType === 'Animal' ? groupType + 's' : groupType}}</span>
like image 174
Tushar Avatar answered Sep 13 '26 13:09

Tushar


Yes you can:

<span>{{["Car", "Animal"].indexOf(groupType) >= 0 ? groupType + 's' : groupType}}</span>

I use an array of names with indexOf, because it's a little shorter than "x or y or z"


Ideally, you don't want this logic in your HTML, though. I'd suggest putting it in a function in your controller:

$scope.getGroupType = function(type){
    if(["Car", "Anumal"].indexOf(type) >= 0)
        return type + 's';
    return type;
};

Then, in your HTML:

<span>{{getGroupType(groupType)}}</span>
like image 41
Cerbrus Avatar answered Sep 13 '26 15:09

Cerbrus