Reputation: 66585
After populating the data of users, I would like to display their full name as list elements.
The data binding is set as following:
<ul id="availableOwners">
<!-- ko foreach: OwnersList-->
<li data-bind="text: FirstName, click: AddOwnerToUser.bind($data), value: Id" style="cursor: pointer"></li>
<!-- /ko -->
</ul>
I wanted to display the full name with javascript function:
<li data-bind="text: function() { return FirstName + ' ' + LastName }, click: AddOwnerToUser.bind($data), value: Id" style="cursor: pointer"></li>
However, it displays the listing of the function definition literally as follows:
function () { return FirstName + ' ' + LastName}
function () { return FirstName + ' ' + LastName}
function () { return FirstName + ' ' + LastName}
...
Does anyone know how to display full names correctly in case of binding the list this way?
Upvotes: 2
Views: 1558
Reputation: 7958
To concatenate multiple observables
together you need to evaluate them by use ()
.
E.g:
<li data-bind="text: FirstName() + ' ' + LastName(), click:AddOwnerToUser.bind($data), value: Id" style="cursor:pointer"></li>
However, ideally, you should use a computed observable instead:
self.FullName = ko.computed(function () {
return self.Firstname() + ' ' + self.LastName();
}
<li data-bind="text: FullName, click:AddOwnerToUser.bind($data), value: Id" style="cursor:pointer"></li>
Upvotes: 6
Reputation: 1782
With more complicated models, instead of over-filling your view/html file, you might consider using a computed observable:
this.FullName = ko.computed(function () {
return this.Firstname() + ' ' + this.LastName();
}
Upvotes: 1