I want to combine a knockout data-bind: text
with a hard coded text like the example below:
<h6 data-bind="text: username + 'are now logged in'"></h6>
I have tried several different pluses and semicolons etc but couldn't make it work.
You need to execute observables to get their value:
ko.applyBindings({ username: ko.observable("johndoe") });
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<h6 data-bind="text: username() + 'are now logged in'"></h6>
Better is though to use a (pure)Computed observable, which you can unit test:
function ViewModel() {
var self = this;
self.username = ko.observable("johndoe");
self.loggedInMessage = ko.pureComputed(function(){
return self.username() + " is now logged in";
});
}
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<h6 data-bind="text: loggedInMessage"></h6>
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