如何在AngularJS部分中保留新行?

时间:2013-03-16 12:35:49

标签: angularjs

在AngularJS部分中,我循环遍历条目列表,如下所示:

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

{{entry.content}}的内容有一些被AngularJS忽略的换行符。如何使其保留换行符?

4 个答案:

答案 0 :(得分:103)

这只是基本的HTML。 AngularJS不会改变任何相关内容。您可以使用pre代码:

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

或者使用CSS:

p .content {white-space: pre}

...

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

如果entry.content包含HTML代码,您可以使用ng-bind-html

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

不要忘记包含ngSanitize

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

答案 1 :(得分:35)

我制作过滤器

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

然后

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

答案 2 :(得分:12)

我通过添加pre-line来修复它:

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

答案 3 :(得分: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>