Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs if-then-else construction in expression

Can I somehow use if-then-else construction (ternary-operator) in angularjs expression, for example I have function $scope.isExists(item) that has to return bool value. I want something like this,

<div ng-repeater="item in items">     <div>{{item.description}}</div>     <div>{{isExists(item) ? 'available' : 'oh no, you don't have it'}}</div> </div> 

I know that I can use function that returns string, I'm interesting in possibility of using if-then-else construction into expression. Thanks.

like image 398
IgorCh Avatar asked May 16 '13 09:05

IgorCh


People also ask

What is the correct syntax to write an expression in AngularJS?

AngularJS expressions can be written inside double braces: {{ expression }} . AngularJS expressions can also be written inside a directive: ng-bind="expression" .

Which operator replaces if else construct?

The conditional operator – also known as the ternary operator – is an alternative form of the if/else statement that helps you to write conditional code blocks in a more concise way. First, you need to write a conditional expression that evaluates into either true or false .

What is :: In AngularJS?

It's used to bind model from your controller to view only. It will not update your controller model if you change this from your view. It means it's used to achieve one time binding. Example. angular.


2 Answers

Angular expressions do not support the ternary operator before 1.1.5, but it can be emulated like this:

condition && (answer if true) || (answer if false) 

So in example, something like this would work:

<div ng-repeater="item in items">     <div>{{item.description}}</div>     <div>{{isExists(item) && 'available' || 'oh no, you don't have it'}}</div> </div> 

UPDATE: Angular 1.1.5 added support for ternary operators:

{{myVar === "two" ? "it's true" : "it's false"}} 
like image 77
Andre Goncalves Avatar answered Sep 27 '22 01:09

Andre Goncalves


You can use ternary operator since version 1.1.5 and above like demonstrated in this little plunker (example in 1.1.5):

For history reasons (maybe plnkr.co get down for some reason in the future) here is the main code of my example:

{{true?true:false}} 
like image 31
Sebastian Avatar answered Sep 27 '22 01:09

Sebastian