Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS textarea linebreak/newline conversion

I have a textarea with content populated through ng-model:

<textarea data-ng-model="messageBody"></textarea>

messageBody needs to be stored in the database using newline characters (\n) instead of line breaks. However, when I use regex to convert newline to linebreak and pass that to the model, angular escapes the HTML. Is there a way to pass the HTML directly to the model or textarea without it being converted? Or, is there a better way to convert between textarea line breaks and newline characters?

UPDATE

On further inspection, this wasn't an angular problem. We are populating the database (Postgres) using an SQL script. Turns out the strings inserted into the database weren't escaped. Since the strings contained a newline character, that means they were being inserted directly as text. Then, line break handling from the front end seemed to be producing inconsistent results from what was initially populated. Long story short - I escaped the initial database content to accommodate for the newline character, and everything works fine.

like image 288
Eric Di Bari Avatar asked Nov 01 '22 21:11

Eric Di Bari


1 Answers

New lines inside a textarea are new lines in the resulting string (\n).

This fiddle demonstrates such behaviour.

If you want to store \n in the database, there is nothing to do, the string is already of that format.

If by 'linebreak', you mean the <br> tag and you actually meant that the string comes from the DB containing such tags, then you should replace them beforehand I suppose.

Ideally your database should contain newlines (\n), you should save and fetch newlines from it as is, no conversion.

like image 133
JJJ Avatar answered Nov 11 '22 04:11

JJJ