Greg Finzer
Greg Finzer

Reputation: 7054

if statement binding short circuiting in Knockout.js

I would like to hide a span if the value is null or simply show an empty string. The if statement is not short circuiting so I am wrapping the whole statement in a div.

Here is what I have now that is working:

<div data-bind="if: Allergen()"><span data-bind="text: Allergen().Name"></span></div> 

Here is what I would like to do:

<span data-bind="if: Allergen(), text: Allergen().Name"></span>

Is there a coalesce or something in knockout?

Upvotes: 3

Views: 1339

Answers (1)

Ilya
Ilya

Reputation: 29673

You can use virtual if bindings

<!-- ko if: Allergen() -->  
<span data-bind="text: Allergen().Name"></span>
<!-- /ko -->    

Or use visible-binding instead (but it's not null-safe)

<span data-bind="visible: Allergen(), text: Allergen() ? Allergen().Name : '' "></span>

JSFiddle DEMO

Upvotes: 2

Related Questions