I am trying to render the following with knockout.
<!-- ko with: address-->
<!-- ko if: address1-->
<span style="display : block">
<span data-bind="varchar : address1"></span>
</span>
<span style="display : block">
<span data-bind="varchar : address2"></span>
</span>
<!-- /ko -->
<!-- /ko -->
The problem is that even if the address object is present it may not contain the address1 parameter. I'd like knockout to not render the nested spans if the parameter 'address1' is null. Currently the following error is thrown:
Unable to parse bindings. Message: ReferenceError: address1 is not defined;
Any help much appreciated.
If you use <!-- ko if: $data.address1 -->
, then it will not error out if address1
is undefined.
If address1
does later become populated, it will not update the UI though (address1
would need to be an observable originally).
Isn't it just a case of moving your second if?
<!-- ko with: address -->
<span style="display : block">
<!-- ko if: address1 -->
<span data-bind="varchar : address1"></span>
<!-- /ko -->
</span>
<span style="display : block">
<span data-bind="varchar : address2"></span>
</span>
<!-- /ko -->
Looks like we need to see your viewModel and how addresses relate to each other. I can do that on the sample from knockout page with no problems:
<h1 data-bind="text: city"> </h1>
<p data-bind="with: coords">
<!-- ko if: latitude -->
Latitude: <span data-bind="text: latitude"> </span>,
<!-- /ko -->
Longitude: <span data-bind="text: longitude"> </span>
</p>
I had a case where I had an address template being called from different places.
My 'country name' data field was sometimes countryName
and sometimes countryDesc
.
I just changed the template to this:
<div data-bind="text: $data.countryName || $data.countryDesc"></div>
This takes advantage of the fact that if you use $data
it won't error out (as pointed out by RP Niemeyer)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With