Reputation: 10408
I have a simple template with an if binding inside it:
<script type="text/html" id="addPersonTemplate">
<tr>
...
<td class="large-7" data-bind="text: addPersonUsername"><span class="noSpecificChecks" data-bind="if: addPersonUsername() == false">No username added</span></td>
...
</tr>
</script>
Basically, a person has an option to enter a username. When they click 'add' somewhere else in the document, the template is outputted, however, no matter what I try:
I cannot get if: addPersonUsername() == false
to evaluate correctly.
If the expression evaluates to true (there is no username) I want to output "No username added". Yet, if I enter no username, the addPersonUsername() variable is undefined (checked via console.log
) and yet this text is not outputted.
Is there any particular reason for this? Is the if binding only evaluated at HTML page load, not at template addition? I can't see any indication it is...
Upvotes: 1
Views: 257
Reputation: 139748
Knockout observables are functions so you need to get their value with calling them without any argument (e.g.: addPersonUsername()
) when they are used in any expression like inside an if
binding:
<span class="noSpecificChecks" data-bind="if: addPersonUsername() == false">
Beside that your HTML is structured incorrectly. When you apply the text
binding on the td
it replaces the whole content of the td
so also your span with the if
.
So you need to apply the text something else inside the td
like on a span
(or use the virtual element syntax if you don't need the span
):
<td class="large-7" >
<!-- ko if: addPersonUsername -->
<span data-bind="text: addPersonUsername"></span>
<!-- /ko -->
<span class="noSpecificChecks" data-bind="if: addPersonUsername() == false">No username added
</span>
</td>
Demo JSFiddle.
Upvotes: 2