I have a data binding in Knockout to apply a CSS class if a condition is true. When I use a dash in the class name (such as test-class) then I get a javascript error.
Here is a fiddle that demonstrates the problem: http://jsfiddle.net/sgvem/2/
<p data-bind="text: property, css: { with-dash: property().length > 0 }"></p>
Is there a way to add a class with a dash using Knockout JS?
A binding context is an object that holds data that you can reference from your bindings. While applying bindings, Knockout automatically creates and manages a hierarchy of binding contexts. The root level of the hierarchy refers to the viewModel parameter you supplied to ko. applyBindings(viewModel) .
KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.
Just put it in quotes:
<p data-bind="text: property, css: { 'with-dash': property().length > 0 }"></p>
Here's an updated fiddle.
As a side note, you don't need the > 0
since a length
of 0
will evaluate to false
, and any other length will evaluate to true
:
<p data-bind="text: property, css: { 'with-dash': property().length }"></p>
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