Caner
Caner

Reputation: 873

if else condition with Knockout

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?

Upvotes: 5

Views: 21694

Answers (2)

Hemant D
Hemant D

Reputation: 192

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>

Upvotes: 2

Bryan Dellinger
Bryan Dellinger

Reputation: 5304

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>

Upvotes: 5

Related Questions