admin管理员组文章数量:1320612
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.
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.
Share Improve this question edited May 29, 2015 at 7:36 José Ricardo Pla 1,04310 silver badges16 bronze badges asked May 29, 2015 at 6:49 Alan AlcockAlan Alcock 7872 gold badges11 silver badges27 bronze badges 2- if(!bool || typeof bool == undefined) bool='No'; else bool='Yes'; ? Don't see why you would replace fully functional boolean values though. – JazzCat Commented May 29, 2015 at 6:53
- Apologies @JazzCat. Hope my edit makes clarifies my question. You can see what I am trying to achieve from the markup. – Alan Alcock Commented May 29, 2015 at 7:05
2 Answers
Reset to default 8You 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
本文标签: javascriptYes or No instead of True or False in KnockoutStack Overflow
版权声明:本文标题:javascript - Yes or No instead of True or False in Knockout - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742083713a2419848.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论