Erez
Erez

Reputation: 1953

Binding a class from the viewModel to a div with an existing hard coded class in knockout

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.

Upvotes: 0

Views: 102

Answers (1)

nemesv
nemesv

Reputation: 139778

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.

Upvotes: 1

Related Questions