javascript - 使用 ng-bind-html 进行自动换行

标签 javascript html angularjs ng-bind-html

我正在使用 AngularJS 构建个人笔记管理应用程序。在此过程中,我遇到了一些问题,我可以选择我的错误:我是否应该拥有一个无法自动换行的应用程序或一个无法感知返回键的应用程序。

首先,我的应用程序不会检测到返回键或额外的空格,因此,在我的 note 指令中,我替换了: <p>{{note.body}}</p> 和: <p ng-bind-html="note.body | format"></p>


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

App with ng-bind-html

使用 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使背景、边框等不可见之后。

最佳答案

将此 css 类添加到您的 <p>或您想使用的任何标签:

.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 />");
    }
  };
});

关于javascript - 使用 ng-bind-html 进行自动换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32126578/

相关文章:

javascript 对象 - 如何绑定(bind)到 "this"

javascript - websockets ws.on 和 ws.onmessage 之间的区别

javascript - 创建元素功能不起作用

javascript - 当 AngularJS 中没有 ngRepeated 时,如何在我的 DOM 中排序?

javascript - 访问元素值

javascript - 日期时间选择器 - Chrome 和 Firefox 之间的奇怪行为

javascript - 限制 JavaScript 函数中输入的值

php - 删除 JQuery 库后 JQuery 仍然存在

HTML 属性编码

javascript - 需要 12 小时格式而不显示 AM/PM Timepicker