我正在尝试使用多个过滤器,如下所示
<p><span ng-bind-html="someVar | nl2br | linky"></span></p>
什么都没有。 但是,当我更改过滤器的顺序时,如下所示
<p><span ng-bind-html="someVar | linky | nl2br"></span></p>
linky有效,但是nl2br无法将换行符转换为br。
以下实现可用于nl2br:
.filter('nl2br', function($sce) {
return function(input) {
return $sce.trustAsHtml( input.replace(/\n/g, '<br>') );
}
}
答案 0 :(得分:8)
所以我能够使用someVar | linky | nl2br
。问题在于链接过滤器。 ngSanitize的linky过滤器分别将\ r和\ n更改为
和
。给定nl2br过滤器无法捕获那些。
感谢这个要点https://gist.github.com/kensnyder/49136af39457445e5982,修改后的nl2br如下
angular.module('myModule')
.filter('nl2br', ['$sanitize', function($sanitize) {
var tag = (/xhtml/i).test(document.doctype) ? '<br />' : '<br>';
return function(msg) {
// ngSanitize's linky filter changes \r and \n to and respectively
msg = (msg + '').replace(/(\r\n|\n\r|\r|\n| | | | )/g, tag + '$1');
return $sanitize(msg);
};
}]);
工作小提琴http://jsfiddle.net/fxpu89be/4/
然而,它仍然没有解决以相反顺序使用它的原始问题,即someVar | nl2br | linky
答案 1 :(得分:1)
以zeroflagL的评论为基础 - 将其保持正常状态直至结束。
<p><span ng-bind-html="someVar | nl2br | linky | trustMe"></span></p>
删除所有信任 - 以便我们返回正常的字符串:
.filter('nl2br', function($sce) {
return function(input) {
return input.replace(/\n/g, '<br>');
}
}
我们要做的最后一件事是增加一些信任:
.filter('trustMe', function($sce) {
return function(input) {
return $sce.trustAsHtml( input ) );
}
}