Knockout binding css class to an observed model pr

2020-06-07 01:30发布

I want to bind a divs css class to a property of the view model like this:

<div id="statusIndicator" data-bind="css: selectedPriority">

But this generates the result:

 <div id="statusIndicator" class=" 0 1 2 3">

This is the view model:

myViewModel = {
    selectedPriority: ko.observable('High'),
    Company: ko.observable("Bert"),
    Rows: ko.observableArray([
         new row(),
         new row(),
         new row()
    ]),
    Tabs: ['High', 'Medium', 'Low'],

    selectPriority: function (tab) {
        this.selectedPriority(tab);
    }
};

So when i load the page that uses this view model i want the div to be:

<div id="statusIndicator" class="High">

What am i doing wrong?

标签: knockout.js
3条回答
相关推荐>>
2楼-- · 2020-06-07 02:08

For this situation you can do:

<div data-bind="attr: { 'class': selectedPriority}">

The only downside to this method is that it will set the class directly rather than toggle a class on or off, so if you are using multiple classes, then selectedPriority would need to contain the complete list of classes.

查看更多
Bombasti
3楼-- · 2020-06-07 02:11

Looks like you can't set a class directly from your model: http://knockoutjs.com/documentation/css-binding.html

You can't do something like this:

 <div data-bind="css: { high: selectedPriority() == 1, medium: selectedPriority() == 2}">
查看更多
你好瞎i
4楼-- · 2020-06-07 02:17

As hinted at in comments by @Chris Jaynes, Knockout 2.2.0 makes setting class names easy, as detailed in a blog post by Knockout author Steve Sanderson.

http://blog.stevensanderson.com/2012/10/29/knockout-2-2-0-released/

As per the post:

We’ve also made some features work more like you might always have thought they should work. For example, the css binding can now attach programmatically-generated CSS class names to elements (previously, it was limited to toggling predefined CSS class names)

The blog post also includes a jsfiddle you can play with to see the binding in action. http://jsfiddle.net/qRmfH/light/

Note the css binding syntax in his example, css: chosenTicketCss, which is a computed observable that returns a css class name:

<p data-bind="visible: chosenTicket, css: chosenTicketCss">
    Excellent choice! Suits you perfectly.
</p>
查看更多
登录 后发表回答