Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout.js carraige return in paragraph text

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.

like image 202
Martin Avatar asked Jul 02 '13 10:07

Martin


People also ask

How do you insert a line break in textarea?

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!

What is $root in knockout?

$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.

What is two way binding in knockout JS?

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.

How does Ko identify the template block that needs to be rendered?

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.


2 Answers

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

like image 160
DevZer0 Avatar answered Oct 08 '22 21:10

DevZer0


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

like image 33
Damien Avatar answered Oct 08 '22 19:10

Damien