Search code examples
angularjsline-breakstext-formatting

Format a text before displaying it in Angularjs


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.


Solution

  • 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'