Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to data-bind the 'class' or 'id' attribute of a div, while using containerless control flow?

Tags:

knockout.js

I am trying out the great new containerless control flow (new feature number 2) at Knockout 2.0.0 released or http://jsfiddle.net/StevenSanderson/8vms5/light

<ul>     <li><strong>Here is a static header item</strong></li>     <!-- ko foreach: products -->     <li>         <em data-bind="text: name"></em>         <!-- ko if: manufacturer -->                    &mdash; made by <span data-bind="text: manufacturer.company"></span>         <!-- /ko -->     </li>     <!-- /ko --> </ul> 

What if i wanted something like < li class="${ name }">< /li>

This was trivial while using templates, but i cannot make it work right now.
i tried < li data-bind='class: name'>< /li> but in vain.

I'm new here, please go easy on me.

like image 312
nthapa Avatar asked Feb 16 '12 04:02

nthapa


People also ask

How do you bind a class in HTML?

Class binding with Class There are another shorthand way to bind CSS Class to HTML element. className is name of the class, which you want to bind to. condition must return true or false. A return value of true adds the class and a false removes the class.

What is data bind attribute?

A data binding connects data from a custom element (the host element) to a property or attribute of an element in its local DOM (the child or target element). The host element data can be a property or sub-property represented by a data path, or data generated based on one or more paths.

What happens in if binding?

The if binding causes a section of markup to appear in your document (and to have its data-bind attributes applied), only if a specified expression evaluates to true (or a true -ish value such as a non- null object or nonempty string).


1 Answers

You can use the css binding. It can be used two ways. Either with a dynamic class (or list of classes):

<li data-bind="css: name"></li> 

or with individual classes bound against truthy/falsy values to indicate whether that are should be added/removed from the element:

<li data-bind="css: { classOne: hasClassOne, classTwo: hasClassTwo }"></li> 
like image 96
RP Niemeyer Avatar answered Sep 26 '22 21:09

RP Niemeyer