Skip to content

Instantly share code, notes, and snippets.

@charlypoly
Forked from naoyeye/angular.filters.nl2br.js
Last active August 29, 2015 14:06
Show Gist options
  • Save charlypoly/2550ea170034db9691e5 to your computer and use it in GitHub Desktop.
Save charlypoly/2550ea170034db9691e5 to your computer and use it in GitHub Desktop.
use strict compliant version + handle undefined case
/*
# 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>
*/
'use strict';
angular.module('myApp')
.filter('nl2br', function($sce){
return function(msg,isXhtml) {
if (!angular.isString(msg)) {
return '';
} else {
isXhtml = isXhtml || true;
msg = (msg + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ (isXhtml ? '<br />' : '<br>') +'$2');
return $sce.trustAsHtml(msg);
}
};
});
@nblum
Copy link

nblum commented Dec 2, 2014

Nice solution, works perfect

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