将新行 /n 转换为 angular 中的换行符

新手上路,请多包涵

我有一个包含换行符 /n 的字符串。试图显示

字符串。它没有将 /n 作为新行,而是将“/n”显示为文本。

    $scope.myOutput = " Hello /n"

    {{ myOutput | textFormat }}

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

试过:

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

尝试过 css 样式,例如 white-space: pre;

原文由 Rk R Bairi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 968
2 个回答

这不会取代它,但您可以使用 CSS 属性 white-space: pre-line; 在浏览器中呈现 \n: https ://developer.mozilla.org/en-US/docs/Web/CSS/white -空间

 div {
  white-space: pre-line;
}
 <div>Foo
   Bar
       Baz     Foo
     Bar



  Baz
</div>

原文由 Tim Schoch 发布,翻译遵循 CC BY-SA 4.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'

原文由 Vadim Shashkov 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题