Is there any way to pluralize some text using knockoutjs
-
25-10-2019 - |
سؤال
Text data-bind expressions can have only a single property. How would I pluralize some text depending on the count of another property?
المحلول
There are several ways to do this. I demonstrated 2 ways in the fiddles shown here: http://jsfiddle.net/njj2P/2/
The first option I showed is to use a ko.computed to determine if the name should be returned in singular or plural form, based on an evaluation.
this.formattedName = ko.computed(function() {
return this.qty() > 1 ? this.name() + "s" : this.name();
}, this);
The second option shows how to do this without a computed property, and instead by using a conditional binding.
<span data-bind="if:qty()>1">s</span>
نصائح أخرى
You can create a reusable custom binding like the following.
ko.bindingHandlers.pluralize = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
function count(data) {
var value = ko.utils.unwrapObservable(data);
if (typeof value === "object" && value.length > 0) {
return value.length;
} else if (typeof value === "number") {
return value;
}
}
var settings = valueAccessor();
var text = count(settings.data) === 1 ? settings.singular : settings.plural;
$(element).text(ko.utils.unwrapObservable(text));
}
};
You would use it like this.
<span data-bind="pluralize: { data:items, singular:'entry', plural:'entries' }"></span>
- The
data
option can point to any array or number. - The
singular
option represents the text you want to display ifdata
evaluates to 1 - The
plural
option represents the text that will be displayed otherwise.
See it in action here. http://fiddle.jshell.net/jessegavin/wamfw/
لا تنتمي إلى StackOverflow