Angularjs if-then-else construction in expression

IgorCh picture IgorCh · May 16, 2013 · Viewed 192.2k times · Source

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.

Answer

Andre Goncalves picture Andre Goncalves · May 16, 2013

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