I am trying to use multiple filters as below,
<p><span ng-bind-html="someVar | nl2br | linky"></span></p>
which renders nothing. However, when I change the order of filters as below
<p><span ng-bind-html="someVar | linky | nl2br"></span></p>
linky works, but nl2br fails to convert line breaks to br.
The following implementation can be used for nl2br:
.filter('nl2br', function($sce) {
return function(input) {
return $sce.trustAsHtml( input.replace(/\n/g, '<br>') );
}
}
So I was able to get it work with someVar | linky | nl2br
. The problem was with linky filter. ngSanitize's linky filter changes \r and \n to
and
respectively. Given nl2br filter fails to catch those.
Thanks to this gist https://gist.github.com/kensnyder/49136af39457445e5982 , modified nl2br as follows
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);
};
}]);
Working fiddle http://jsfiddle.net/fxpu89be/4/
However, it still doesn't solve the original problem of using it in reverse order i.e someVar | nl2br | linky
Building on zeroflagL's comment - keep it a normal sting until the end.
<p><span ng-bind-html="someVar | nl2br | linky | trustMe"></span></p>
Removing all trust - so that we return a normal string:
.filter('nl2br', function($sce) {
return function(input) {
return input.replace(/\n/g, '<br>');
}
}
The last thing we want to do is add some trust:
.filter('trustMe', function($sce) {
return function(input) {
return $sce.trustAsHtml( input ) );
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With