【问题标题】:Word Wrapping using ng-bind-html使用 ng-bind-html 自动换行
【发布时间】:2015-08-20 19:18:26
【问题描述】:

我正在使用 AngularJS 构建个人笔记管理应用程序。在此期间,我遇到了一些问题,我需要选择我的 bug:我应该拥有一个不能自动换行的应用程序还是一个不能感知返回键的应用程序。

起初,我的应用程序不会感知返回键或多余的空格,因此,在我的 note 指令中,我替换了: <p>{{note.body}}</p> 和: <p ng-bind-html="note.body | format"></p>


虽然它解决了输入键的问题,但它不会自动换行:

使用 ng-bind-html,自动换行失败 - 这对我的应用程序来说太可怕了,因为我希望它在调整大小时非常灵活。

我该如何解决这个错误?

这是我的格式过滤器: angular.module('NoteWrangler') .filter('format', function (){ return function(input) { if(!input) return input; var output = input //replace possible line breaks. .replace(/(\r\n|\r|\n)/g, '<br/>') //replace tabs .replace(/\t/g, '&nbsp;&nbsp;&nbsp;') //replace spaces. .replace(/ /g, '&nbsp;'); return output; }; });

注意指令:

```<div class="container note note-full">
    <h2>{{note.title}}</h2>
    <p ng-bind-html="note.body | format"></p>
    <p class="text-muted date">Posted on {{note.timestamp | date}}</p>
</div>```

如果使用标签是解决此问题的唯一方法,那么我会这样做 - 在我使用一些 CSS 使背景、边框等不可见之后。

【问题讨论】:

    标签: javascript html angularjs ng-bind-html


    【解决方案1】:

    将此 css 类添加到您的 &lt;p&gt; 或您要使用的任何标签:

    .text-pre-wrap{
        white-space: pre-wrap !important;
    }
    

    另外你只需要这个作为你的过滤器

    angular.module('NoteWrangler').filter('format', function () {
      return function (input) {
        if (input) {
          return input.replace(/\n/g, "<br />");
        }
      };
    });
    

    【讨论】:

    • 只是好奇:我不能在我的样式表中使用[ng-bind-html] { ... } 来修复每个标签的所有问题,或者由于某种原因这会是不好的做法吗?
    • 对此不确定,但由于您使用&lt;p&gt; 标记大部分内容,我建议将此属性关联为类似p {white-space: pre-wrap !important; }
    【解决方案2】:

    添加属性

    .text-pre-wrap{
        white-space: pre-wrap !important;
    }
    

    对我来说不够

    我还需要补充:

    .text-pre-wrap{
        white-space: pre-wrap !important;
        overflow-wrap: break-word;
    }
    

    在 html 中:

    <div ng-bind-html="notes.html" class="text-pre-wrap"></div>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-27
      • 1970-01-01
      相关资源
      最近更新 更多