angular: create formating filter without html-escaping

749 Views Asked by At

I want to do automatic html formatting for some strings. For example, I want to do automatic subscripts for a char that is prefixed with an underline.
So a string like "U_1 + U_2 = U_3" should be formatted to U1 + U2 = U3

This looks like a perfect job for a filter. I tried the following:

angular.module('myApp.filters', []).
  filter('convert_subscripts', [ function(){
      return function(text){
          return text.replace(/_([\w]+)/, '<sub>$1</sub>', 'g');
      };
   }])

And in my view:

<p>{{content.text | convert_subscripts }}</p>

But this escapes the HTML, so the user sees the "sub" tags instead of a nicely formatted subscript.

How do I implement a formatting function so that the html-Tags are not escaped?

(To be perfect, the content.text itself should be escaped for security, but the added subscript-tags not. I use angular 1.2)

1

There are 1 best solutions below

0
On

I think this article should help. You can render the html as it is by two ways

$sce.trustAsHtml('text')

or you can create a filter for this purpose like

app.filter('filterName',function($sce){
    return function(text){
             $sce.trustAsHtml(text);
           }
    });

In your case you should use approach 1

function($sce){
      return function(text){
          return $sce.trustAsHtml(text.replace(/_([\w]+)/, '<sub>$1</sub>', 'g'));
      };