【问题标题】:How to display a string with new lines as a string with <br />'s in AngularDart?如何在AngularDart中将带有新行的字符串显示为带有<br />的字符串?
【发布时间】:2014-05-27 09:53:18
【问题描述】:

鉴于我在 AngularDart 的页面上显示了一个字符串。

... <strong>Notes: </strong> {{cmp.selectedStudent.notes}} ...

如何让它显示多行?在我有换行符的字符串中,我希望它们在 html 输出中被编码为 &lt;br /&gt; 字符。

【问题讨论】:

    标签: dart angular-dart


    【解决方案1】:

    您可以将字符串中的 '\n' 替换为 &lt;br/&gt; 并使用类似于我在此处的答案 How to add a component programatically in Angular.Dart? 中显示的建议的 my-bind-html 指令(由于最近的许多更改,该代码可能有点过时角)

    您可以使用ng-repeat 并在您的笔记行上重复,但首先您需要将它们按'\n' 拆分,以便获得一组行。

    List<String> _notesList = null; 
    List<String> get notesList { 
      if (_notesList==null) _notesList = notes.split("\n").toList(); return _notesList; 
    } 
    

    .

    <span ng-repeat="note in cmp.selectedStudent.notesList">{{note}}<br /></span>
    

    【讨论】:

    • 好的,谢谢 List 可以使用 ng-repeat。列表 _notesList = null; List get notesList { if (_notesList==null) _notesList = notes.split("\n").toList();返回_notesList; } {{note}}
    【解决方案2】:

    默认情况下,Angular 不会解释 HTML 应答器以避免一些不可预测的行为或其他坏事,但您可以使用

    禁用此验证

    ng-bind-html

    官方文档链接:NgHtmlBind

    因此您可以直接将 '\n' 字符替换为 'br' html 节点。

    所以你可以这样做:

    // ...
    String getHtmlBrNote() {
      return this.notes.replaceAll("\n", "<br />");
    }
    // ...
    

    在角度之后

    ... <strong>Notes: </strong> <span ng-bind-html="cmp.selectedStudent.getHtmlBrNote()"></span> ...
    

    会没事的

    【讨论】:

    • ng-bind-html 没有移植到 Dart 中,出于安全原因也不打算移植。我的答案中的链接显示了构建您自己的 ng-bind-html 指令端口的代码。
    • 我刚刚在 AngularDart 官方文档NgHtmlBind 中看到了这一点,我已经在 Dartium 中测试了我的代码并且它可以工作。但也许它已经贬值了
    • 好的,我得试试。它说它评估为一个字符串,也许它转义了所有&lt;&gt;&amp;...,但为什么它需要一个NodeValidator。也许这已经随着几周前自定义 NodeValidator 的推出而改变了。
    • 我认为这是因为在角度过程中,NgHtmlBind 的处理是在之后进行的,如果它不是字符串,它可能会破坏角度解析器或类似的东西。 但这只是一个想法,我没有检查自己。
    • 感谢您引起我的注意。自从我上次检查此指令以来,确实发生了变化。我会再试一次,但可能不是今天。
    猜你喜欢
    • 2017-12-20
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 2012-11-11
    • 1970-01-01
    • 2023-03-20
    • 2021-09-19
    • 1970-01-01
    相关资源
    最近更新 更多