没有其他html的angularjs换行符过滤器 [英] angularjs newline filter with no other html
问题描述
我正在尝试将换行符 (\n
) 转换为 html br
.
根据 Google 群组中的讨论,我得到了以下信息:
I'm trying to convert newline characters (\n
) to html br
's.
As per this discussion in the Google Group, here's what I've got:
myApp.filter('newlines', function () {
return function(text) {
return text.replace(/\n/g, '<br/>');
}
});
那里的讨论还建议在视图中使用以下内容:
The discussion there also advises to use the following in the view:
{{ dataFromModel | newline | html }}
这似乎使用了旧的 html
过滤器,而现在我们应该使用 ng-bind-html
属性.
This seems to be using the old html
filter, whereas now we're supposed to use the ng-bind-html
attribute.
无论如何,这会带来一个问题:我不希望原始字符串 (dataFromModel
) 中的任何 HTML 呈现为 HTML;只有 br
的.
Regardless, this poses a problem: I don't want any HTML from the original string (dataFromModel
) to be rendered as HTML; only the br
's.
例如,给定以下字符串:
For example, given the following string:
虽然 7 > 5
我仍然不想要 html &这里的东西...
While 7 > 5
I still don't want html & stuff in here...
我希望它输出:
While 7 > 5<br>I still don't want html & stuff in here...
有没有办法做到这一点?
Is there any way to accomplish this?
推荐答案
我决定使用 2 个过滤器,而不是使用新指令:
Instead of messing with new directives, I decided to just use 2 filters:
App.filter('newlines', function () {
return function(text) {
return text.replace(/\n/g, '<br/>');
}
})
.filter('noHTML', function () {
return function(text) {
return text
.replace(/&/g, '&')
.replace(/>/g, '>')
.replace(/</g, '<');
}
});
然后,在我看来,我将一个管道连接到另一个:
Then, in my view, I pipe one into the other:
<span ng-bind-html-unsafe="dataFromModel | noHTML | newlines"></span>
这篇关于没有其他html的angularjs换行符过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!