if else condition with Knockout
Asked Answered
I

2

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?

Interchangeable answered 24/7, 2017 at 19:26 Comment(2)
Check out the if bindingCzechoslovak
You should be checking the enable binding knockoutjs.com/documentation/enable-binding.htmlFreighter
M
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>
Mondragon answered 24/7, 2017 at 20:10 Comment(0)
D
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>
Delano answered 21/9, 2017 at 13:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.