miquelarranz miquelarranz - 2 years ago 72
AngularJS Question

Format a text before displaying it in Angularjs

I have a text like:

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.

Answer Source

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>


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>


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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download