Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
angular nl2br filter
/*
# Usage in html template:
"xxx | nl2br"
<div ng-bind-html=" YourString | nl2br "></div>
or:
"xxx | nl2br:Boolean"
Boolean( true or flase or just keep null) means is xhtml or not
if is xhtml, replace with <br/> ; if not , replace with <br>
<div ng-bind-html=" YourString | nl2br:true "></div>
-------------------------
# Example:
//==Analog data===
$scope.items = [
{"message": "test"},
{"message": "New\nLine"},
]
//=====
<div class="comment" ng-repeat="item in items">
<p ng-bind-html=" item.message | nl2br "></p>
</div>
-------------------------
# Output result:
<div class="comment ng-scope" ng-repeat="item in items">
<p class="ng-binding" ng-bind-html=" item.message | nl2br ">
test
</p>
</div>
<div class="comment ng-scope" ng-repeat="item in items">
<p class="ng-binding" ng-bind-html=" item.message | nl2br ">
New<br>Line
</p>
</div>
*/
angular.filter('nl2br', function($sce){
return function(msg,is_xhtml) {
var is_xhtml = is_xhtml || true;
var breakTag = (is_xhtml) ? '<br />' : '<br>';
var msg = (msg + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
return $sce.trustAsHtml(msg);
}
});
@niyando

This comment has been minimized.

Copy link

@niyando niyando commented Jan 29, 2015

@kensnyder

This comment has been minimized.

Copy link

@kensnyder kensnyder commented Feb 25, 2015

@niyando, @naoyeye - ngSanitize's linky filter changes \r and \n to &#10; and &#13; respectively so this nl2br filter doesn't catch those. See my fork of this gist here. It allows you to do ng-bind-html="text | linky | nl2br"

@niyando

This comment has been minimized.

Copy link

@niyando niyando commented Mar 30, 2015

Thanks @kensnyder. Nice catch. This fixes my issue.

@Gigabyte1979

This comment has been minimized.

Copy link

@Gigabyte1979 Gigabyte1979 commented Jul 10, 2015

Thank you!

@rbaarsma

This comment has been minimized.

Copy link

@rbaarsma rbaarsma commented Feb 1, 2016

Is there a way to use this without allowing all other HTML too?

$scope.text = "This is <b>nonsafe</b> html\nThis is safe!";

<p ng-bind-html="text | nl2br"></p>

(this also makes the nonsafe tekst bold.. but what if I don't want that?)

@wiesys

This comment has been minimized.

Copy link

@wiesys wiesys commented Feb 8, 2016

Thanks – this does almost exactly what I need 👍
There is only one "mistake" if I could say so: var is_xhtml = is_xhtml || true; There is no way that is_xhtml could be false:

false || true == true
undefined || true == true
'' || true == true

I suggest var is_xhtml = (typeof is_xhtml == 'undefined) ? false : true;

@zzlalani

This comment has been minimized.

Copy link

@zzlalani zzlalani commented May 1, 2016

nice one, Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment