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.
Note: Using “if” and “ifnot” without a container element-- ko --> and <! -- /ko --> comments act as start/end markers, defining a “virtual element” that contains the markup inside. Knockout understands this virtual element syntax and binds as if you had a real container element.
In a data binding process, each data change is reflected automatically by the elements that are bound to the data. The term data binding is also used in cases where an outer representation of data in an element changes, and the underlying data is automatically updated to reflect this change.
The "data-bind" attribute contains a collection of comma-separated options for how Knockout should bind a view model property to an HTML element. The two examples above use only a single option: the "value" binding handler.
You haven't provided enough info, but we can safely assume one of two situations:
DtCntrctDlvry = 0
; orDtCntrctDlvry = 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:
Plain properties:
<span data-bind="text: DtCntrctDlvry === 0 ? 'a' : 'b'"></span>
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:
==
where you might prefer ===
?'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.
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