我正在使用 AngularJS 构建个人笔记管理应用程序。在此过程中,我遇到了一些问题,我可以选择我的错误:我是否应该拥有一个无法自动换行的应用程序或一个无法感知返回键的应用程序。
首先,我的应用程序不会检测到返回键或额外的空格,因此,在我的 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, ' ')
//replace spaces.
.replace(/ /g, ' ');
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/