Preserve line breaks in angularjs

Diolor picture Diolor · Oct 30, 2013 · Viewed 153.5k times · Source

I have seen this SO question.

My code instead of ng-bind="item.desc" uses {{item.desc}} because I have a ng-repeat before.

So my code:

<div ng-repeat="item in items">
  {{item.description}}
</div>

The item description contains \n for newlines which are not rendered.

How can the {{item.description}} display the newlines easily assuming that I have the ng-repeat above?

Answer

Paul Weber picture Paul Weber · Oct 1, 2014

Based on @pilau s answer - but with an improvement that even the accepted answer does not have.

<div class="angular-with-newlines" ng-repeat="item in items">
   {{item.description}}
</div>

/* in the css file or in a style block */
.angular-with-newlines {
    white-space: pre-wrap;
}

This will use newlines and whitespace as given, but also break content at the content boundaries. More information about the white-space property can be found here:

https://developer.mozilla.org/en-US/docs/Web/CSS/white-space

If you want to break on newlines, but also collapse multiple spaces or white space preceeding the text (very similar to the original browser behaviour), you can use, as @aaki suggested:

white-space: pre-line;

Nice comparison of the different rendering modes: http://meyerweb.com/eric/css/tests/white-space.html