How can I preserve new lines in an AngularJS partial?

Angularjs

Angularjs Problem Overview


Within an AngularJS partial I am looping over a list of entries as follows:

<ul class="entries">
    <li ng-repeat="entry in entries">
        <strong>{{ entry.title }}</strong>
        <p>{{ entry.content }}</p>
    </li>
</ul>

The content of {{entry.content}} have some linebreaks which are ignored by AngularJS. How can I make it preserve the linebreaks?

Angularjs Solutions


Solution 1 - Angularjs

It is just basic HTML. AngularJS won't change anything about that. You could use a pre tag instead:

<pre>{{ entry.content }}</pre>

Or use CSS:

p .content {white-space: pre}

...

<p class='content'>{{ entry.content }}</p>

If entry.content contains HTML code, you could use ng-bind-html:

<p ng-bind-html="entry.content"></p>

Don't forget to include ngSanitize:

var myModule = angular.module('myModule', ['ngSanitize']);

Solution 2 - Angularjs

I make filters

// filters js
myApp.filter("nl2br", function($filter) {
 return function(data) {
   if (!data) return data;
   return data.replace(/\n\r?/g, '<br />');
 };
});

then

// view
<div ng-bind-html="article.description | nl2br"></div>

Solution 3 - Angularjs

I fix it by adding pre-line:

<style>
    pre{
        white-space: pre-line;
    }
</style>
My data:
 <pre>{{feedback.Content}}<pre>

Solution 4 - Angularjs

// AngularJS filter
angular.module('app').filter('newline', function($sce) {
    return function(text) {
        text = text.replace(/\n/g, '<br />');
        return $sce.trustAsHtml(text);
    }
});

// HTML
<span ng-bind-html="someText | newline"></span>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmythView Question on Stackoverflow
Solution 1 - AngularjsasgothView Answer on Stackoverflow
Solution 2 - AngularjsNawlbergsView Answer on Stackoverflow
Solution 3 - AngularjsMike NguyenView Answer on Stackoverflow
Solution 4 - Angularjsyashesh_damaniView Answer on Stackoverflow