IgorCh IgorCh - 25 days ago 14
Javascript Question

Angularjs if-then-else construction in expression

Can I somehow use if-then-else construction 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.

Answer

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"}}
Comments