How to use nl2br and linky filters together in Angularjs?

I am trying to use multiple filters as shown below

<p><span ng-bind-html="someVar | nl2br | linky"></span></p> 

which does nothing. However, when I change the order of the filters as shown below

 <p><span ng-bind-html="someVar | linky | nl2br"></span></p> 

linky works, but nl2br cannot convert line breaks to br.

For nl2br, you can use the following implementation:

 .filter('nl2br', function($sce) { return function(input) { return $sce.trustAsHtml( input.replace(/\n/g, '<br>') ); } } 
+5
source share
2 answers

So I managed to get it to work with someVar | linky | nl2br someVar | linky | nl2br someVar | linky | nl2br . The problem was with the link filter. ngSanitize linky filter changes \ r and \ n to &#10; and &#13; respectively. This nl2br filter cannot catch them.

Thanks to this gist https://gist.github.com/kensnyder/49136af39457445e5982 , modified by nl2br as follows

 angular.module('myModule') .filter('nl2br', ['$sanitize', function($sanitize) { var tag = (/xhtml/i).test(document.doctype) ? '<br />' : '<br>'; return function(msg) { // ngSanitize 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); }; }]); 

Working fiddle http://jsfiddle.net/fxpu89be/4/

However, it still does not solve the original problem of using it in the reverse order. i am someVar | nl2br | linky someVar | nl2br | linky

+6
source

Based on comments from ZeroflagL - keep it in good condition until the end.

 <p><span ng-bind-html="someVar | nl2br | linky | trustMe"></span></p> 

Removing all trust - so that we return the normal string:

 .filter('nl2br', function($sce) { return function(input) { return input.replace(/\n/g, '<br>'); } } 

The last thing we want to do is add trust:

 .filter('trustMe', function($sce) { return function(input) { return $sce.trustAsHtml( input ) ); } } 
+1
source

Source: https://habr.com/ru/post/1211702/


All Articles