user2402107 user2402107 - 4 months ago 23
AngularJS Question

Textarea with New Lines after Comma Angularjs

I am new to front-end development and I am trying to figure out the best approach to utilizing a text area that has a new line after each comma. I am really trying to figure out what the best approach would be in AngularJs(filter,Regex,etc.)

Now:

hello,how,are,you


After:

Hello
how
are
you


currently:

<textarea cols="105" rows="30" disabled="true"
style="background-color: floralwhite; resize: none; white-space: normal; margin-top: 0px; border: none;">
{{profile.exampleValues}}
</textarea>


I tried to write a filter with no luck:

.filter('newlines', function () {
return function (text) {
return text.replace(',', '<br/>');
}
})

Answer

I updated your code to get it working.

First of all, white-space: normal; was replaced by white-space: pre-line;

Secondly, the filter was improved to deal with a regular expression. According to W3C:

The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.

Note: If you are replacing a value (and not a regular expression), only the first instance of the value will be replaced. To replace all occurrences of a specified value, use the global (g) modifier

app.filter('newlines', function () {
  return function (text) {
    return text.replace(/,/g, '\n');
  };
});

As a result, the textarea should look like:

<textarea cols="105" rows="30" disabled="true"
          style="background-color: floralwhite; white-space: pre-line; resize: none; margin-top: 0px; border: none;">
    {{profile.exampleValues | newlines}}
</textarea>

Please look at the Plunker.