Text binding useful to display text without any html element (plain text). According to HTML , normally we write text inside span or p tag but it can be used with any element.
Important note is that it will overwritten previous text and it will consider html element as plain text if written.
Let’s go for an example and check how in different conditions and variously uses.
Simple Example:
1 2 3 4 5 6 7 8 |
The item is <span data-bind="text: stockMessage"></span>. <script type="text/javascript"> var viewModel = { stockMessage: ko.observable("Out of Stock") }; ko.applyBindings(viewModel); </script> |
In above example, we have bind stockMessage as text with initial value as “Out of stock”.
Condition based Example:
in below example, we have put condition, based on that it changes the stockMessage observable.
1 2 3 4 5 6 7 8 9 10 11 12 |
The item is <span data-bind="text: stockMessage"></span>. <script type="text/javascript"> var viewModel = { stockMessage: ko.observable("In Stock") }; var qty = 9; if(qty < 10){ viewModel.stockMessage("Out of stock"); } ko.applyBindings(viewModel); </script> |
We can also use Container less syntax. What it is? Question ?
It’s simple instead of data-bind inside of HTML element we can write like this.
1 |
The item is <span><!--ko text: stockMessage --><!--/ko--></span>. |
Directly can use knockout observable to same logic of condition based message.
1 2 3 4 5 6 7 8 |
The item is <span data-bind="text: qty() < 10 ? 'Out of Stock' : 'In Stock' "></span>. <script type="text/javascript"> var viewModel = { qty: ko.observable() }; viewModel.qty(5); ko.applyBindings(viewModel); </script> |