Reputation: 3867
I have a textarea with content populated through ng-model:
<textarea data-ng-model="messageBody"></textarea>
messageBody needs to be stored in the database using newline characters (\n) instead of line breaks. However, when I use regex to convert newline to linebreak and pass that to the model, angular escapes the HTML. Is there a way to pass the HTML directly to the model or textarea without it being converted? Or, is there a better way to convert between textarea line breaks and newline characters?
UPDATE
On further inspection, this wasn't an angular problem. We are populating the database (Postgres) using an SQL script. Turns out the strings inserted into the database weren't escaped. Since the strings contained a newline character, that means they were being inserted directly as text. Then, line break handling from the front end seemed to be producing inconsistent results from what was initially populated. Long story short - I escaped the initial database content to accommodate for the newline character, and everything works fine.
Upvotes: 6
Views: 23769
Reputation: 19
Yes, you can do this in AngularJS with "SCE / Strict Contextual Escaping". Continue to convert the newline to a linebreaks and pass that to the model.
Then when you show the data in your template, you can use $sce.trustAsHtml()
to preserve the HTML content, then ng-bind-html
directive to bind it to the DOM. Here is an example of how it would appear in the controller:
myApp.controller( 'contentCtrl', [ '$scope', '$sce', function( $scope, $sce ){
$scope.messageBody = $sce.trustAsHtml( 'Hello <br> World' );
}]);
Then in your template, bind it like this:
<div ng-bind-html="messageBody"></div>
More Info on $sce
here in the AngularJS Docs.
Upvotes: 0
Reputation: 340
New lines inside a textarea are new lines in the resulting string (\n
).
This fiddle demonstrates such behaviour.
If you want to store \n
in the database, there is nothing to do, the string is already of that format.
If by 'linebreak', you mean the <br>
tag and you actually meant that the string comes from the DB containing such tags, then you should replace them beforehand I suppose.
Ideally your database should contain newlines (\n
), you should save and fetch newlines from it as is, no conversion.
Upvotes: 1