javascript - with - typescript line break




AngularJS String with newlines, shown without breaks (3)

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.

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.



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.





angularjs