In Knockout is there a clean way to display a boolean property from my view model to show 'Yes' or 'No' instead of True / False. Sometimes the property is undefined so this should also show No.
Currently using :
<td data-bind="text: isAvailable ? 'Yes' : 'No'"></td>
Must be a better way.
You could use this custom bindingHandler,
ko.bindingHandlers.YesNo = {
update: function (element, valueAccessor) {
// defaults to false
var val = ko.utils.unwrapObservable(valueAccessor()) || false;
if (val)
$(element).text("Yes");
else
$(element).text("No");
}
}
Use it like so,
<td data-bind="YesNo: isAvailable"></td>
Thanks
if you define isAvailable as observable you can easily achieve it by:
JSFIDDLE
ViewModel
var viewModel = function()
{
var self = this;
self.isAvailable = ko.observable(false);
};
View
<td data-bind="text: $root.isAvailable() ? 'Yes' : 'No'"></td>
p/s: don't forget to use () when dealing with observable value
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