Search code examples
htmlangularjstextareamultilinesanitize

AngularJS: Writing to and Reading from textarea with multilines


I can't believe why I can't find anything to this topic ... I got a form with let's say lastname (input), firstname (input), description (textarea as I want provide several lines). Let's start with the creation of a new object:

Okay, you type something in like

lastname: fox

firstname: peter

description:

what can I say ..
well I'm THE guy

bye

This arrives at my Java Spring MVC Backend Controller as what can I say ..\nwell I'm THE guy\n\nbye which is fine as I can determine where line breaks are.

So, now I want to edit this object. Thus I want to read the stored data and put it in the form. On Serverside I now edited the description text so that I replaced the \n with <br> so that I have HTML breaks.

Now I use angular-sanitize (ngSanitize dependency) and use the directive ng-bind-html="my.nice.description"

If I use this on a DIV, everything works fine, HTML gets rendered and I get my breaks. So this works perfectly:

<span ng-bind-html="my.nice.description"></span>

or one of the following:

<div ng-bind-html="my.nice.description"></div>
<p ng-bind-html="my.nice.description"></p>

BUT as I want to (re)fill my form so the user can edit his previous input, I still use a textarea. Like this:

<textarea ng-bind-html="my.nice.description"></textarea>

And this does NOT work in any way. Which means that I get
's in my text, unrendered.

Though this seems like a ridicilous normal task. It's a form with a simple multiline box, so I want to write my several lines and I want to read them and I want to edit them. As I am rather a backend guy and not very familiar with HTML and AngularJS I hope that I'm just using the wrong html element or something like this ... Maybe someone can help me out? It's frustrating :(

Thanks in advance and I guess and hope this is not a real hard task :x


Solution

  • <textarea> elements cannot contain other elements (in your case, <br>'s). They are standalone. You'll have to convert the variable-returned-from-server-containing-<br>'s back to \n's, and vice versa back and forth. You can use an angular directive that handles that for you.