Danielle
Danielle

Reputation: 3839

Conditional "With" binding on data-bind

Using knockout JS, how can I apply a conditional with binding to HTML?

I have two observables, either one should be used based on a condition for the same html code. I want to do something like this:

if some-condition:

<div data-bind="with: observable1">

else:

<div data-bind="with: observable2">

      <!-- the below is common code -->             
      <label data-bind: "text: observable-property"></label>
      <!-- .... -->

</div>

Upvotes: 0

Views: 1016

Answers (2)

Nisarg Shah
Nisarg Shah

Reputation: 14561

<div data-bind="with: var1() ? var2 : var3">
  <div data-bind="text: a">
  </div>
</div>

You can bind an observable conditionally to the with binding like this.

See this fiddle for a demo.

Upvotes: 3

Brother Woodrow
Brother Woodrow

Reputation: 6382

You could use comment tags:

<!-- ko if: foo -->
<div data-bind="with: bar"></div>
<!-- /ko -->
<!-- ko ifnot: foo -->
<div data-bind="with: baz"></div>
<!-- /ko -->

Upvotes: 0

Related Questions