Using knockout.js, how do I include a carriage return in the text that is bound to the text attribute of a paragraph <p>
element.
In my ViewModel I generated a string of text that is bound to the <p>
in the View. I want to include carriage returns in the string which the browser displays with the line breaks.
Including <br />
or Environment.NewLine
in the string does not seem to work.
To add line breaks to a textarea, use the addition (+) operator and add the \r\n string at the place where you want to add a line break, e.g. 'line one' + '\r\n' + 'line two' . The combination of the \r and \n characters is used as a newline character. Here is the HTML for the examples in this article. Copied!
$root. This is the main view model object in the root context, i.e., the topmost parent context. It's usually the object that was passed to ko. applyBindings . It is equivalent to $parents[$parents.
KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.
Shorthand syntax: If you just supply a string value, KO will interpret this as the ID of a template to render. The data it supplies to the template will be your current model object.
You need to set a css property in your element. white-space: pre-wrap
<p style="white-space: pre-wrap">First name: <strong data-bind="text: firstName">todo</strong></p> <p>Last name: <strong>todo</strong></p> function AppViewModel() { this.firstName = "Bert" + " \n " + "Test"; this.lastName = "Bertington"; } // Activates knockout.js ko.applyBindings(new AppViewModel());
Then the code works. with \n
You can use the html binding.
JS:
function AppViewModel() { this.firstName = "Bert<br\>Test"; this.lastName = "Bertington"; } // Activates knockout.js ko.applyBindings(new AppViewModel());
View :
<p>First name: <strong data-bind="html: firstName">todo</strong></p> <p>Last name: <strong>todo</strong></p>
See fiddle
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