I'm having difficulties getting the style binding working in KnockoutJS.
<script id="avatarTemplate" type="text/x-jquery-tmpl">
<div id="avatar_${id}" class="avatar" data-bind="style:
{ background: s, width: '50px', height: '85px', left: (x + 'px'), top:
(y + 'px') }">${s}, ${x}, ${y}</div>
</script>
<div data-bind="template: { name: 'avatarTemplate', foreach: avatars }"></div>
The result of rendering this template is:
<div id="avatar_1" class="avatar" style="width: 50px; height: 85px;">avatar.png, 0, 0</div>
Can anyone help me figure out why all styles which are dependent on the view model do not show up?
The css binding adds or removes one or more named CSS classes to the associated DOM element. This is useful, for example, to highlight some value in red if it becomes negative. (Note: If you don't want to apply a CSS class but instead want to assign a style attribute value directly, see the style binding.)
Style binding is used to set a style of a view element. We can set the inline styles of an HTML element using the style binding in angular. You can also add styles conditionally to an element, hence creating a dynamically styled element.
If x
and y
are observables, then you need to specify it like this:
<div id="avatar_${id}" class="avatar" data-bind="style:
{ background: s, width: '50px', height: '85px', left: (x() + 'px'), top:
(y() + 'px') }">${s}, ${x}, ${y}</div>
If you use an observable in an expression, then it needs to be specified with (), as it won't get unwrapped automatically.
http://jsfiddle.net/rniemeyer/6GtV3/
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