I've a graph chart like below made using css and knockout.js (binding)
Depending on the value of the data, I need to size the height of the bars by selecting different css classes.
I've tried to use the knockout if statement below:
The <!-- ko --> and <!-- /ko --> 
However, this doesn't meet my requirement as I need something like below:
     <ul data-bind="foreach: ArrayData">
      <!-- ko if: value >= 300 and value <=250 -->
            <li class="height300Css">
        <!-- /ko -->
       <!-- ko if: value >= 200 and value <=300 -->
            <li class="height200Css">
        <!-- /ko -->
    </ul>
Could someone suggest any alternatives?
Thanks.
Add a computed observable to your view model that returns the correct css class, then use the "attr" binding (http://knockoutjs.com/documentation/attr-binding.html).
Or use the "css" binding - but that requires you to have the whole selection logic in the view file.
Example code:
var ViewModel = function() {
    var self = this;
    // ....
    self.cssClass = ko.computed(function() {
        var value = self.value();
        if (value >= 300 && value <= 250) {
            return 'height300Css';
        }
        // ...
    };
};
And in the view:
<li data-bind="attr: { class: cssClass }"> 
If you're dealing with an array of objects, you can either add the computed observable to those objects or you can add a normal function to the view model and call it during the foreach loop.
var ViewModel = function() {
    var self = this;
    self.items = ko.observableArray(...);
    self.getCssClass = function(item) {
        var value = item.value();
        // ...
    };
};
And in the view:
<li data-bind="attr: { class: $root.getCssClass($data) }">
Demo: http://jsbin.com/awacew
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