user1400915 user1400915 - 7 months ago 9
HTML Question

Controlling styles in knockoutjs based on the values

I have two divs generated dynamically using knockoutbinding as follows:

<div id="simdivs" data-bind="text:$data.Name,visible:$data.Name !== undefined"></div>


I want to conditionally give a css styling as
"margin-left:1px"
if the data.Name from the second div is "" (empty) else
"margin-left:0px"

how do I achieve this using knockout js?

Answer

Use the Style data-bind

<div id="simdivs" data-bind="style: {marginLeft: $data.Name === null ? '1px' : '0px'}></div>

Do note that it is written as marginLeft instead of margin-left