5

I'm very new at Knockout. I have a problem, how can I use if/else with Knockout.

For example like this

<ul class="list-group" data-bind="foreach: users">
    <li class="list-group-item" data-bind="click : setasUser">
        <i class="fa fa-circle text-success"></i> <span data-bind="text: name"></span>
    </li>
</ul>

I want to have a non-clikable item if username == x

How can I do this?

Talha Awan
  • 4,573
  • 4
  • 25
  • 40
Caner
  • 813
  • 1
  • 12
  • 26
  • Check out the [if binding](http://knockoutjs.com/documentation/if-binding.html) – JNevill Jul 24 '17 at 19:31
  • You should be checking the `enable` binding http://knockoutjs.com/documentation/enable-binding.html – gkb Aug 08 '17 at 05:25

2 Answers2

5

unfortunately knockout does not have if else. however it does have an if binding and a ifnot binding.

here is a fiddle. http://jsfiddle.net/LkqTU/35843/

<ul class="list-group" data-bind="foreach: users">
<!-- ko ifnot: username() === 'x' -->
    <li class="list-group-item" data-bind="click : $parent.setasUser">
        <i class="fa fa-circle text-success"></i> <span data-bind="text: name"></span>
    </li>
  <!-- /ko -->
  <!-- ko if: username() === 'x' -->
  <li class="list-group-item" data-bind="text: name"> </li>
   <!-- /ko -->
</ul>
Bryan Dellinger
  • 4,724
  • 7
  • 33
  • 79
2

Simply you can set the click event function on based on your condition like below

<ul class="list-group" data-bind="foreach: users">
    <li class="list-group-item" data-bind="click : username !== x ? setasUser: null">
        <i class="fa fa-circle text-success"></i> <span data-bind="text: name"></span>
    </li>
</ul>
Hemant D
  • 192
  • 5