保留angularjs中的换行符
我看过这个问题。
我的代码而不是ng-bind="item.desc"使用{{item.desc}}因为我之前有一个ng-repeat 。 
所以我的代码:
 <div ng-repeat="item in items"> {{item.description}} </div> 
 项目描述包含\n为不是呈现的换行符。 
  {{item.description}}如何轻松地显示换行符,假设我有上面的ng-repeat ? 
尝试:
 <div ng-repeat="item in items"> <pre>{{item.description}}</pre> </div> 
  <pre>包装器将以\n作为文本打印文本 
 另外如果你打印的JSON,为了更好的看看使用jsonfilter,如: 
 <div ng-repeat="item in items"> <pre>{{item.description|json}}</pre> </div> 
演示
 我同意@Paul Weber那个white-space: pre-wrap; 是更好的方法,反正使用<pre> – 快速的方式主要是debugging一些东西(如果你不想浪费时间的样式) 
基于@ pilau的答案 – 但有一个改善,即使是接受的答案没有。
 <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; } 
这将使用换行符和空白符号,但是也会在内容边界处分割内容。 更多关于白色空间的信息可以在这里find:
https://developer.mozilla.org/en-US/docs/Web/CSS/white-space
如果要在换行符上打破,也要在文本之前折叠多个空格或空格(与原始浏览器行为非常相似),则可以使用@aaki提示:
 white-space: pre-line; 
不同渲染模式的比较: http : //meyerweb.com/eric/css/tests/white-space.html
这是如此简单的CSS(它的工作,我发誓)。
 .angular-with-newlines { white-space: pre; } 
- 看你妈! 没有额外的HTML标签!
用CSS可以轻松实现。
 <div ng-repeat="item in items"> <span style="white-space:pre-wrap;"> {{item.description}}</span> </div> 
或者可以为此创build一个CSS类,并可以从外部CSS文件中使用
CSS解决scheme的作品,但是你真的不能控制的样式。 在我的情况下,我想在换行之后再多一点空间。 这里是我创build来处理这个(打字稿)的指令:
 function preDirective(): angular.IDirective { return { restrict: 'C', priority: 450, link: (scope, el, attr, ctrl) => { scope.$watch( () => el[0].innerHTML, (newVal) => { let lineBreakIndex = newVal.indexOf('\n'); if (lineBreakIndex > -1 && lineBreakIndex !== newVal.length - 1 && newVal.substr(lineBreakIndex + 1, 4) != '</p>') { let newHtml = `<p>${replaceAll(el[0].innerHTML, '\n\n', '\n').split('\n').join('</p><p>')}</p>`; el[0].innerHTML = newHtml; } } ) } }; function replaceAll(str, find, replace) { return str.replace(new RegExp(escapeRegExp(find), 'g'), replace); } function escapeRegExp(str) { return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"); } } angular.module('app').directive('pre', preDirective); 
使用:
 <div class="pre">{{item.description}}</div> 
 它所做的就是将文本的每个部分都包装到一个<p>标签中。 之后,你可以不pipe你想要的样式。 
 那么这取决于,如果你想绑定数据,不应该有任何格式,否则你可以bind-html和做description.replace(/\\n/g, '<br>')不知道这是什么你想要的。 
 是的,我会使用<pre>标记或使用ng-bind-html-unsafe http://docs-angularjs-org-dev.appspot.com/api/ng.directive:ngBindHtmlUnsafe (使用ng-bind-html如果您使用的是1.2+),使用.replace()将/n更改为<br /> 
只要使用CSS风格的“空白:预先包装”,你应该很好去。 我有同样的问题,我需要处理错误信息的线断和空格是真的特别。 我刚刚添加这个内联我绑定数据,它的作品像魅力!