Last active
March 22, 2016 15:32
-
-
Save ryandrewjohnson/47b0cf01781cbedcec8b to your computer and use it in GitHub Desktop.
Render user entered line breaks to the DOM with this AngularJS filter.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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