Convert multiline text to HTML paragraphs using AngularJS

I get multi-line text from my backend.

For instance:

Lorem ipsum dolor sit amet, <strong>consectetur</strong> adipiscing elit. Nunc porta velit ut nunc pretium, quis auctor nunc placerat. In quis porta neque. Fusce dapibus faucibus mi ut egestas. <p>Phasellus egestas magna posuere, bibendum dui quis, lacinia nisl.</p> 

I want to make it using AngularJS as HTML paragraphs.

So this example will become:

 <p>Lorem ipsum dolor sit amet, &lt;strong&gt;consectetur&lt;/strong&gt; adipiscing elit.</p> <p>Nunc porta velit ut nunc pretium, quis auctor nunc placerat. In quis porta neque. Fusce dapibus faucibus mi ut egestas.</p> <p>&lt;p&gt;Phasellus egestas magna posuere, bibendum dui quis, lacinia nisl.&lt;/p&gt;</p> 

Please note that all HTML that existed in the source code must be safely escaped (including existing <p> ), so I can’t just apply a filter and do the evacuation afterwards.

I view it as a three-step process:

  • Exclusion of HTML inclusions in the source text.
  • Apply a filter to break multi-line text into paragraphs.
  • Display text without further escaping.

But I'm not sure what is the best way to implement each step.

Could you guide me with a suitable vector? Thanks!

+6
source share
2 answers

I think I finally solved this problem. Hope this answer helps someone.

As I mentioned earlier, this is a three-step process.

  • Exclusion of HTML inclusions in the source text.
  • Apply a filter to break multi-line text into paragraphs.
  • Display text without further escaping.

For the first step, I tried to find some existing function to delete the source text, but to no avail. It seems that AngularJS does not reveal any ways to do this (please correct me if I am wrong). Finally, I created my own filter to avoid HTML:

 myModule.filter('htmlEscape', function() { return function(input) { if (!input) { return ''; } return input. replace(/&/g, '&amp;'). replace(/</g, '&lt;'). replace(/>/g, '&gt;'). replace(/'/g, '&#39;'). replace(/"/g, '&quot;') ; }; }); 

Then I created a filter to break simple text into paragraphs:

 myModule.filter('textToHtml', ['$sce', 'htmlEscapeFilter', function($sce, htmlEscapeFilter) { return function(input) { if (!input) { return ''; } input = htmlEscapeFilter(input); var output = ''; $.each(input.split("\n\n"), function(key, paragraph) { output += '<p>' + paragraph + '</p>'; }); return $sce.trustAsHtml(output); }; }]) 

I insert the previously created htmlEscape filter to it and using the $sce.trustAsHtml method to return a value suitable for use with the ng-bind-html directive.

And at the end, I call this filter in a partial template as follows:

 <div ng-bind-html="someText|textToHtml"></div> 

Here is the result:

Result of applying the filter

+9
source

I would look at using the ng-sanitze module in the Angular API. I think this should cover what you are looking for.

$ sanitize

-2
source

All Articles