Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply ternary operator inside an expression which uses a filter

Tags:

angularjs

this works:

{{ boolean ? String1 : String2 }}

this doesn't:

{{ boolean ? String1 | weirdoFilter : String2 | weirdoFilter }}

How can I apply filters to ternary expressions ?

edit: Maybe single quotes?

like image 438
AME Avatar asked Aug 21 '15 11:08

AME


People also ask

Can we use ternary operator inside ternary operator?

For example, you should not try to make ternary operators nested inside of ternary operators. Although writing code this way works correctly in JavaScript, it is very hard to read and understand.

How do I apply for a ternary operator?

Example: C Ternary Operatorage >= 18 - test condition that checks if input value is greater or equal to 18. printf("You can vote") - expression1 that is executed if condition is true. printf("You cannot vote") - expression2 that is executed if condition is false.

Can we use ternary operator in LINQ query?

We can simply use a ternary operator or we can even use a nested ternary operator.

How do you handle 3 conditions in a ternary operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.


2 Answers

You can do it with parenthesis :

{{ (boolean ? String1 : String2) | weirdoFilter }}
like image 144
Pierre-Alexandre Moller Avatar answered Oct 21 '22 15:10

Pierre-Alexandre Moller


... if you make a function in your view, then it becomes easier to do logic in your controller using real life javascript (instead of more limited angular expressions)...

{{ mySpecificThing(String1,String2) }}

... then in controller ...

$scope.mySpecificThing = function(item1, item2){
    return boolean ? $filter('weirdoFilter')(item1) : $filter('weirdoFilter')(item2);
}

As a general pattern, I think it is favourable to always keep your logic away from your templates.

like image 21
Billy Moon Avatar answered Oct 21 '22 14:10

Billy Moon