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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With