Search code examples
htmlknockout.jsdata-bindingknockout-3.0

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>

Solution

  • <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.