0

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)

Meier
  • 3,858
  • 1
  • 17
  • 46
  • @codeHater: That gives me an runtime error: Error: [$sce:unsafe] Attempting to use an unsafe value in a safe context. http://errors.angularjs.org/1.2.0/$sce/unsafe I think there was some changes in angular 1.2. – Meier Nov 11 '13 at 11:15
  • 1
    Oh right. You would need to inject `$sce` service into your controller and call the `$sce.trustAsHtml` method. Have a look here: http://stackoverflow.com/questions/19625850/angularjs-1-2-0-ngbindhtml-and-trustashtml-not-working-with-ngmodel – AlwaysALearner Nov 11 '13 at 11:33
  • Yes, this worked (I injected $ice in the filter definition). – Meier Nov 11 '13 at 13:39

1 Answers1

0

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'));
      };
Ekansh Rastogi
  • 2,418
  • 2
  • 14
  • 23