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?
For this situation you can do:
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.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:
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:
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: