Nil Pun
Nil Pun

Reputation: 17383

Knockout if else Statement

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.

Upvotes: 4

Views: 18604

Answers (2)

Jason Goemaat
Jason Goemaat

Reputation: 29234

Can you just use the css binding?

<ul id="MyList" data-bind="foreach:list">
    <li>
        <span data-bind="text: value, css: { height300Css: value >= 250 && value <= 300, height200Css: value >= 200 && value < 250 }"></span>
    </li>
</ul>

BTW I'm sure it's just pseudocode, but value can never be >= 300 AND <= 250, and you need to use && instead of 'and', so I changed the expressions for my fiddle so 200-249 would be red and 250-300 would be blue.

Upvotes: 3

Niko
Niko

Reputation: 26730

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

Upvotes: 13

Related Questions