Skip to content

Instantly share code, notes, and snippets.

@elchingon
Forked from kensnyder/angular.filters.nl2br.js
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elchingon/f422df19fea6fac0e6cc to your computer and use it in GitHub Desktop.
Save elchingon/f422df19fea6fac0e6cc to your computer and use it in GitHub Desktop.
/*
# 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>
<!-- or with linky -->
<p ng-bind-html=" item.message | linky | 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.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);
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment