Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>') );
  }
}
like image 707
Nirav Gandhi Avatar asked Jan 22 '15 13:01

Nirav Gandhi


2 Answers

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

like image 64
Nirav Gandhi Avatar answered Nov 19 '22 13:11

Nirav Gandhi


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 ) );
  }
}
like image 2
Remento Avatar answered Nov 19 '22 12:11

Remento