Skip to content

Instantly share code, notes, and snippets.

@ryandrewjohnson
Last active March 22, 2016 15:32
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 ryandrewjohnson/47b0cf01781cbedcec8b to your computer and use it in GitHub Desktop.
Save ryandrewjohnson/47b0cf01781cbedcec8b to your computer and use it in GitHub Desktop.
Render user entered line breaks to the DOM with this AngularJS filter.
/**
* When a user enters copy into a <textarea> and adds line breaks
* that information is ignored by defualt if you were to save it
* and then display the copy in the DOM.
*
* For example I enter this copy into a text area and save it:
* <textarea>
* My name is Ryan
* and I'm a web developer.
* </textarea>
*
* If I display that saved copy in the DOM it would render without line break:
* <p>My name is Ryan and I'm a web developer.</p>
*
* Using this filter will ensure the line breaks are displayed.
* <textarea ng-model="vm.bodyText"></textarea>
*
* <p ng-bind-html="vm.bodyText"></p>
*
* NOTE: You must use the "ng-bind-html" directive to render text as the filter
* inserts "<br/>" tags for line breaks.
*/
(function() {
'use strict';
angular
.module('app', [])
.filter('lineBreak', lineBreak);
lineBreak.$inject = [];
function lineBreak() {
return filterFilter;
////////////////
function filterFilter(text) {
if (!text || !text.length) {
return text;
}
return text.replace(/(\r\n)/gmi, '<br/>');
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment