Knockout - How to bind outer container css from set of checkboxes?

£可爱£侵袭症+ 提交于 2020-01-15 04:05:26

问题


OK, admittedly horrible grammar in the question, but here's the lowdown:

I'm using the following in my site:

  • Twitter Bootstrap
  • Knockout
  • Durandal

I'm trying to add a css class to the outer label surrounding a checkbox (in a list of checkboxes) so it can highlight the selected checkboxes. Essentially the code is this:

<div data-bind="foreach:values">
    <label class="checkbox inline btn" data-bind="css: { }">
        <input type="checkbox" data-bind="attr: { value: text }, checked: $parent.checkedValues" /> 
        <span data-bind="text: text"></span>
    </label>
</div>

So, what I'm trying to do is to add the btn-primary class to the outer label for the checkboxes that are checked. Rather than put the full viewmodel in here, I've created a Fiddle: http://jsfiddle.net/riceboyler/WEPRZ/1/

I recognize that I can use the $data object to get the current item, but I can't figure out how to check and see if the current item ($data.text) is in the checkedValues observableArray. I'm sure it's probably basic Javascript that I'm missing, but is there any way to do this without using a computed value?


回答1:


You can do this directly in the css binding by inspecting the parent's checkedValues array.

<label 
    class="checkbox inline btn" 
    data-bind="css: {'btn-primary': $parent.checkedValues.indexOf(text) > -1}">

See the Fiddle




回答2:


You can try this predicate :

$parent.checkedValues().indexOf($data.text) >= 0

I created a new version your fiddle.

I hope this helps.



来源:https://stackoverflow.com/questions/16319892/knockout-how-to-bind-outer-container-css-from-set-of-checkboxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!