Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout binding css class to an observed model property

Tags:

knockout.js

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?

like image 443
Dave Avatar asked Oct 12 '11 10:10

Dave


People also ask

What is binding in Knockout?

Essentially a binding or a data binding is a way to link your ViewModels to your Views(templates) and vice versa. KnockoutJS uses two-way data binding, which means changes to your ViewModel influence the View and changes to your View can influence the ViewModel.

How do I bind a CSS class in angular 6?

Class binding with Class There are another shorthand way to bind CSS Class to HTML element. className is name of the class, which you want to bind to. condition must return true or false. A return value of true adds the class and a false removes the class.


1 Answers

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.

like image 158
RP Niemeyer Avatar answered Oct 16 '22 06:10

RP Niemeyer