Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the style data bindings?

Tags:

knockout.js

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?

like image 317
fadedbee Avatar asked Jun 15 '11 19:06

fadedbee


People also ask

What is data binding in CSS?

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.)

What is style binding in angular?

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.


1 Answers

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/

like image 190
RP Niemeyer Avatar answered Nov 20 '22 01:11

RP Niemeyer