2

I have a text like:

Blablabla
Hello
How are you?

But it has to be stored in my database in the same text field like this:

Blablabla Hello How are you?

I am using Angular and I would like to know how to format the database text before displaying it inside the template like this.

<p>{{ value }}</p>

I know I should add a separator in the database but I don't know if it's possible to add a '\n' for example and then format the text before displaying it.

5
  • 1
    Make sure the line breaks are in the text in the first place, and use CSS to preserve them: developer.mozilla.org/fr/docs/Web/CSS/white-space Commented Jun 15, 2016 at 9:48
  • How can I make sure the line breaks are in the text? Commented Jun 15, 2016 at 9:52
  • As with any user input sanitize it before sending to the view Commented Jun 15, 2016 at 9:59
  • So using ng-bind-html="trustedHtml" is not unsafe? Commented Jun 15, 2016 at 10:00
  • How can I make sure the line breaks are in the text? By editing the wrong text that is already in the database, and fixing the code that inserts text with line breaks but removes them. Commented Jun 15, 2016 at 10:04

1 Answer 1

4

Try this

In your controller

$scope.value = $scope.value.replace(/\n/g, '<br/>');
$scope.trustedHtml = $sce.trustAsHtml($scope.value);

in your view

<p ng-bind-html="trustedHtml"></p>

OR

you can create a factory to use it everywhere

angular.module('app').filter('trustedHtml', function($sce) {
  return function(val) {
      return $sce.trustAsHtml(val);
  };
});

In your controller

 $scope.value = $scope.value.replace(/\n/g, '<br/>');

in your view

 <p ng-bind-html="value | trustedHtml"></p>

SOLUTION:

 <p ng-bind-html="value"></p>

So Angular $sanitize deletes the tags that may be malicious like 'script'

Sign up to request clarification or add additional context in comments.

3 Comments

The problem is that the text is being sent by users and I think it's not save to display it with ng-blind-html, they can add malicious scripts right?
Yes I think so but using ng-bind-html="trustedHtml" may be unsafe? I mean, can the users inject scripts?
Okay I have used ng-bind-html="value" instead of trustAsHtml, so $sanitize filter the tags that may be unsafe like scripts

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.