Search code examples
angularjsnl2br

How to use nl2br and linky filter together in Angularjs?


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

Solution

  • 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 &#10; and &#13; 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 &#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 doesn't solve the original problem of using it in reverse order i.e someVar | nl2br | linky