45

In the database I'm saving input from a textarea, where you can add breaks. But how to show them in a Angular view? For PHP this is nl2br().

Like <div>{{ item.foobar }}</div>, with breaks shown that are saved like that in the database.

user1469734
  • 851
  • 14
  • 50
  • 81
  • This could also be used to ask/answer the same question about with line breaks(\n) instead of just html breaks(
    ).
    – discodane Mar 24 '17 at 19:55

4 Answers4

105

Binding an HTML seems a bit unsafe. The directive suggested by CuriousGuy has a bit of extra engineering to correctly escape the HTML.

I find it easier to use a styling rule white-space: pre-line.

Example at JSFiddle.

See also:

Thiago Negri
  • 5,221
  • 2
  • 28
  • 39
12

Best solution:

<div class="multi_lines_text">{{ item.foobar }}</div>

<style>
.multi_lines_text { white-space: pre-line; }
</style>

ng-bind-html - it's not safe way and display error in console.

Sergii Semesko
  • 121
  • 1
  • 4
4

If you want to add line breaks only and all the rest text to show as is you can use the following filter:

app.filter('nl2br', function() {
    var span = document.createElement('span');
    return function(input) {
        if (!input) return input;
        var lines = input.split('\n');

        for (var i = 0; i < lines.length; i++) {
            span.innerText = lines[i];
            span.textContent = lines[i];  //for Firefox
            lines[i] = span.innerHTML;
        }
        return lines.join('<br />');
    }
});

then use it in view like this:

<div ng-bind-html="someVar | nl2br"></div>

In this case the only HTML tag that is present in the result string is <br />. All other tags will be escaped.
And don't forget to load ngSanitize module (angular-sanitize.js script).

The full working example you can find on jsFiddle.

Oleg
  • 22,300
  • 9
  • 68
  • 84
  • Any particular reason you don't just do something like `return (input || '').replace(/\n/g, '
    ');`?
    – CWSpear Jul 15 '14 at 22:06
  • @CWSpear The idea is to make `someVar` be shown as simple text, without rendering HTML tags (except `
    ` on the line breaks). You may compare these two jsFiddles: [first](http://jsfiddle.net/mqcpe/6/) and [second](http://jsfiddle.net/mqcpe/4/)
    – Oleg Jul 16 '14 at 06:08
  • 1
    @CWSpear my appologies, here are corrected jsFiddles: [first](http://jsfiddle.net/mqcpe/7/) and [second](http://jsfiddle.net/mqcpe/8/). (StackOverflow doesn't allow editing comments after 5 mins since they were posted) – Oleg Jul 16 '14 at 09:51
1

Googling angularjs nl2br yielded this result:

AngularJS - Remove \n from data

Namely the last answer which demonstrates how to replace new lines with <br /> using a filter. Combine that with ng-bind-html, as the unsafe version might not be currently available. You should probably convert the line breaks to <br /> when inserting them to database(makes more sense to me).

Community
  • 1
  • 1
Erti-Chris Eelmaa
  • 25,338
  • 6
  • 61
  • 78