0

Lets say I have a foreach that creates a div with a class that has to be hard coded (there are position and height of other elements that are set by those divs and called by the class so it can't be calculated only when the binding happens).

I need to add a binded class from the viewModel to that class, but I can't find anywhere on the web how to do this.

example:

<div class="message_image" data-bind="attr: {class : $data.float_class}" >
     <img data-bind='attr:{src: $data.img_url}' />
</div>

I know this is wrong, this is an example for what I am trying to get to....

The "message_image" class has to be hard coded into the html file.

This div has properties that are used way before the knockout is being binded. I need to add the class that is in $data.float_class.

1 Answer 1

1

You need to use the css binding where:

If you want to use dynamic CSS class names, then you can pass a string that corresponds to the CSS class or classes that you want to add to the element.

ko.applyBindings({
    test: [{
        float_class: "float1"
    }, {
        float_class: "float2"
    }]
})
.message_image {
    background: yellow;
}
.float1 {
    color: red;
}
.float2 {
    color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="foreach: test">
    <div class="message_image" data-bind="css: $data.float_class">Test</div>
</div>

Demo JSFiddle.

2
  • It is not exacly the case.... I thought about a solution and implemented it, i am using a hard coded class in the html and binding the extra design to the style attribute. the problem with what you showed here is that u have a model with just classes what you are looping=, i have a very complex viewModel that just one of the values is the class and i can't so the foreach for property, this is not the case.... 10x any way
    – Erez
    Aug 25, 2015 at 12:52
  • You can combine the css and the style binding: use the css for class names and style binding for other css properties... Can you maybe create a jsfiddle/stacksnippet repro? In my example the message_image is hard coded in the HTML and you add the extra classes float1 and float2 with the css binidng, so both classes (hardcoded/bound) are applied (backgroud and text color in the exmample)
    – nemesv
    Aug 25, 2015 at 12:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.