【问题标题】:new lines, br in div plain textdiv 纯文本中的新行,br
【发布时间】:2013-12-23 05:57:05
【问题描述】:

好的,这应该很简单......

使用角度。 我输出一个文本,已经用 textarea 编辑过:

{{model | newline2br}}

如果我不添加过滤器,所有新行都会被忽略。 所以我做了一些谷歌搜索,并写了一个过滤器,newline2br, 就是这样做的——用<br />替换新行

但现在文本显示为文字 <br />!

这是检查窗口中的输出:

<div ng-show="showText" ng-mouseleave="showText = false" class="textwrapper ng-hide">asdjfhaslkjdfh aoiuyqoiweury iufyaoiusydf oiuaysdfiouy aiuysdfoiuy asdfo iuyasdf iouyasdfoiuy asdoifuy aoiusydf oiauysdfoiuays df oiauysdf iouaysdofiuy asioduyf aoiusydf oiauysdfo iuyasdoiufy aoisudyf oiuaysdifuy asdoiufysf<br />hello this is cool<br />I just found out that I can do shift-enter!<br />now I solved the problem with this... :))))</div>

这是为什么呢? 如何正确编写过滤器以便 div 显示新行?

【问题讨论】:

  • 你能在 jsfiddle 上展示你的代码吗?很难确定发生了什么。
  • 好吧,我没有设法让 jsfiddle 运行 angular...但是代码在那里:jsfiddle.net/VLCSL

标签: html angularjs textarea newline


【解决方案1】:

这是因为 AngularJS 默认在字符串中转义 HTML 标记(将它们替换为 HTML 实体),以使您免受 XSS 和其他一些安全问题的影响。要显示未转义的受信任内容,您可以使用 ngBindHTMLUnsafe(在旧 AngularJS 版本中)或 1.2 及更高版本中的 ngBindHTML ans SCE。例如:

<div>{{sometext|newline2br}}</div>

将被改写为(1.2以下):

<div ng-bind-html-unsafe="sometext|newline2br"></div>

1.2及以上版本:

<div ng-bind-html="sometext|newline2br|trusted"></div>

使用受信任的过滤器:

app
  .filter('trusted', function($sce) {
    // You can use this one as `value|newline2br|trusted`, 
    // but I don't recommend it
    return function(input) {
      return $sce.trustAsHtml(input)
    }
  })

或者更好:

<div ng-bind-html="sometext|newline2br"></div>

和:

app
  .filter('newline2br', function($sce) {
    // This is my preferred way
    return function(input) {
      return $sce.trustAsHtml(input.replace(/\n/g, "<br>"))
    }
  })

Plunker:http://plnkr.co/LIxFVpi6ChtTLEni11qy

【讨论】:

    【解决方案2】:

    你可能也应该有这个,否则你将永远看不到文本,因为它永远不会首先出现:

    ng-init="showText=true"
    

    除了 tungd 提到的内容之外,您要寻找的最后一件事是:

    <div class="textwrapper" ng-bind-html-unsafe="model|newline2br" ng-init="showText=true" ng-show="showText" ng-mouseleave="showText = false">
    

    这里是fiddle to demonstrate

    【讨论】:

      【解决方案3】:

      据我了解,您隐藏了 div,因此鼠标永远无法越过它以首先显示 div。

      【讨论】:

      • 好吧,之前有一个封闭的跨度,可以做到这一点,但这与问题无关,我认为:span(ng-mouseover="showText = true")
      • 感谢参与。我在这里找到了答案:stackoverflow.com/questions/15449325/…。我现在使用的是没有过滤器的
         。正确显示新行
      猜你喜欢
      • 2013-12-05
      • 2016-10-15
      • 2010-11-05
      • 2012-08-03
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 2016-10-05
      • 2012-07-10
      相关资源
      最近更新 更多