【问题标题】:convert new line /n to a line break in angular将新行 /n 转换为 angular 中的换行符
【发布时间】:2018-05-22 02:52:52
【问题描述】:

我有一个包含换行符 /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;

【问题讨论】:

    标签: css angularjs whitespace angular-filters linefeed


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      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'

      【讨论】:

        【解决方案3】:

        在 Angular 中,您可以通过如下方式轻松地将文本转换为原始格式:

        组件:

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

        html:

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

        【讨论】:

          猜你喜欢
          • 2021-08-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-09
          • 1970-01-01
          • 1970-01-01
          • 2011-06-29
          • 1970-01-01
          相关资源
          最近更新 更多