5

我正在尝试使用多个过滤器,如下所示,

<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>') );
  }
}
4

2 回答 2

9

所以我能够让它与someVar | linky | nl2br. 问题出在链接过滤器上。ngSanitize 的链接过滤器将 \r 和 \n 分别更改为&#10;&#13;。鉴于 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 &#10; and &#13; respectively
        msg = (msg + '').replace(/(\r\n|\n\r|\r|\n|&#10;&#13;|&#13;&#10;|&#10;|&#13;)/g, tag + '$1');
        return $sanitize(msg);
    };
}]);

工作小提琴http://jsfiddle.net/fxpu89be/4/

但是,它仍然没有解决以相反顺序使用它的原始问题,即someVar | nl2br | linky

于 2015-03-30T18:00:33.383 回答
2

以 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 ) );
  }
}
于 2015-03-29T23:08:19.777 回答