AngularJS String with newlines, shown without breaks

后端 未结 4 866
野趣味
野趣味 2020-12-14 05:54

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

4条回答
  •  佛祖请我去吃肉
    2020-12-14 06:25

    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('
    '); } });

    then use it in view like this:

    In this case the only HTML tag that is present in the result string is
    . 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.

提交回复
热议问题