59

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Amyth
  • 32,527
  • 26
  • 93
  • 135

4 Answers4

105

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']);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
asgoth
  • 35,552
  • 12
  • 89
  • 98
  • Yeah, For the time being i am indeed using a `
    ` tag but I thought there would be an easy to use filter available for angular which now i  doubt. Something like `{{entry.content | pre}}` or `{{entry.content | html}}`
    – Amyth Mar 16 '13 at 13:27
  • @Amyth angular will only treat it as text as does browser. Anything beyond that is up to you – charlietfl Mar 16 '13 at 13:41
  • 4
    For the CSS `white-space` parameter, use `pre-wrap` instead of `pre`. Otherwise long sentences won't be automatically broken into newlines. – thameera Aug 25 '15 at 06:59
  • Don't forget to install ngSanitize to your module! https://docs.angularjs.org/api/ngSanitize/service/$sanitize – Milean Jan 08 '16 at 11:33
35

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>
Nawlbergs
  • 1,012
  • 1
  • 11
  • 10
12

I fix it by adding pre-line:

<style>
    pre{
        white-space: pre-line;
    }
</style>
My data:
 <pre>{{feedback.Content}}<pre>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mike Nguyen
  • 1,024
  • 1
  • 11
  • 16
12
// 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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
yashesh_damani
  • 121
  • 1
  • 4