Knockout - pluralize values
HTML
<script src="https://raw.github.com/SteveSanderson/knockout/master/build/output/knockout-latest.js"></script>
<div>
<p>using computed</p>
<ul data-bind="foreach: products">
<li><span data-bind="text:qty"></span> <span data-bind="text:formattedName"></span></li>
</ul>
<br/>
<p>using conditionals</p>
<ul data-bind="foreach: products">
<li><span data-bind="text:qty"></span> <span data-bind="text:name"></span><span data-bind="if:qty()!=1">s</span></li>
</ul>
</div>
JavaScript
// rbloom, 1/24/2018 - use != instead of > and add hour test case.
var Product = function() {
this.name = ko.observable();
this.qty = ko.observable();
this.formattedName = ko.computed(function() {
return this.qty() != 1 ? this.name() + "s" : this.name();
}, this);
};
var vm = function ViewModel() {
this.products = ko.observableArray([new Product().name("strap").qty(7),
new Product().name("pick").qty(1),
new Product().name("hour").qty(0.5),
new Product().name("bottle").qty(0),
new Product().name("capo").qty(2)]);
};
ko.applyBindings(new vm());