在Angular中如何将换行符"/n"转换为换行符"<br>"?

23

我有一个包含换行符/n的字符串。尝试显示该字符串。但是它并不把/n作为新的一行,而是将其作为文本显示。

   $scope.myOutput = " Hello /n"

    {{ myOutput | textFormat }}

必填项 -> 你好(在html页面上)

尝试过:

 app.filter('textFormat', function() {
    return function(x) {
      return x.replace(/\\n/g, '<br/>');
   }

尝试过像 white-space: pre; 这样的 CSS 样式;


这个回答是否解决了你的问题? angular - 如何在HTML中创建新行 - Vega
3个回答

63

11

在 Angular 中,你可以通过这样输入来轻松将文本转换为原始格式:

组件:

this.myText = 'This is line one\nThis is line 2\nAnd here is 3'

HTML:

<div [innerText]='myText'></div>

0

1 - 将您的过滤器改写成以下方式:

.filter('textFormat', function() {
    return function (x) {
      return x.replace(new RegExp('\/n', 'g'), '<br/>');
    }
 })

2 - 在你的HTML中,你应该使用下面的语法:

<span ng-bind-html="myOutput | textFormat"></span>

其中myOutput$scope.myOutput = ' Hello /n'


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接