Bryan Dellinger
Bryan Dellinger

Reputation: 5304

Using if statement on data-bind text

I can not quite figure out how to put an if statement inside a text binding.

<tbody data-bind="foreach: model.poCollection">
    <tr>
        <td>
            <input type="checkbox">
        </td>
        <td data-bind="text: RlseNbr"></td>
        <td data-bind="text: Clin"></td>
        <td data-bind="text: PrchOrdNbr"></td>
        <td data-bind="text: RqstnCntrlNbr"></td>
        <td data-bind="text: {(DtCntrctDlvry == '0') ? 'a' :'b'}"></td>
    </tr>

Not sure what I am doing wrong the moment I attempt to put the if statement in it the data is no longer displayed.

Upvotes: 6

Views: 21065

Answers (1)

Jeroen
Jeroen

Reputation: 63830

You haven't provided enough info, but we can safely assume one of two situations:

  1. Plain properties: DtCntrctDlvry = 0; or
  2. Observables: DtCntrctDlvry = ko.observable(0)

Binding handlers don't care which it is if you do simple bindings, e.g.:

<span data-bind="text: DtCntrctDlvry"></span>

But they do care if you start putting logic in there. Above situations respectively require:

  1. Plain properties:

    <span data-bind="text: DtCntrctDlvry === 0 ? 'a' : 'b'"></span>
    
  2. Observables:

    <span data-bind="text: DtCntrctDlvry() === 0 ? 'a' : 'b'"></span>
    

In any case, please see my answer to another question where I argue that you would be off even better if you wrap the logic inside a computed, e.g.:

var ViewModel = function() {
  var self = this;
  self.DtCntrctDlvry = ko.observable(0);
  self.DtCntrctDlvryText = ko.computed(function() {
    return self.DtCntrctDlvry() === 0 ? "a" : "b";
  });
}

And bind like this:

<span data-bind="text: DtCntrctDlvryText"></span>

PS. Some footnotes:

  1. Do you realize you're using == where you might prefer ===?
  2. Any reason you're writing '0' (zero, but as a string) instead of 0 (as a number)?

In my answer I've assumed the for both cases you meant to use the latter. If not, you may have to tweak my solution for that.

Upvotes: 10

Related Questions