How can I make conditional binding in knockout.js?

前端 未结 2 2006
野性不改
野性不改 2020-12-31 07:36

I tried this one :

But it does not work :

相关标签:
2条回答
  • 2020-12-31 07:50

    Assuming you have this:

    function viewModel() {
        this.itemSelected = ko.observable(true);
    }
    ko.applyBindings(new viewModel());​
    

    Add a () after itemSelected to get the current value of the observable that you can use with the ternary operator:

    <div data-bind="attr: { class: itemSelected() ? 'selected' : 'unselected' }"></div>​

    http://jsfiddle.net/RK7Ty/


    If you didn't need to assign the unselected class for the non selected state you could do this instead:

    <div data-bind="css: { selected: itemSelected }"></div>​
    

    http://jsfiddle.net/RK7Ty/1/

    0 讨论(0)
  • 2020-12-31 07:57

    Following worked for me, i was using both css and id attributes, for me it did't work if css attribute is not the first one , so keep css attribute as your fist one.

    <div class="panel-collapse collapse" data-bind="css:{in:$index()==0}, attr: { id:'collapse'+$index()} ">
    
    ...
    ...
    ...
    
    </div>
    
    0 讨论(0)
提交回复
热议问题