1

Let's say I have an string that has both CSS and HTML code like this:

<style>.leaf{ color:#0f0; }</style><h1 class="leaf>Tree</h1>

If I use $sce.trustAs($sce.HTML, mystring), it wont render the CSS. Also you cannot concatenate the "trustAs" functions.

So how can you render everything?

2 Answers 2

1

Use angular.element to create an element that you can then append the string to.

Then pull the style tags out of the element and append them to the head of page

This would be done in a preprocessor in controller or service before sending to view

Then let angular sanitize the string and the style will already be in page for it.

  var str='<style>.leaf{ color:#0f0; }</style><h1 class="leaf">Tree</h1>';
  // create element to append string to
  var $el= angular.element('<div>');
  $el.append(str);
  var $style = $el.find('style').addClass('sanitized-style');
  angular.element($document[0].head).append($style);

Remove in destroy of controller

$scope.$on('$destroy', function(){
   angular.element( $document[0].getElementsByClassName('sanitized-style')).remove();
});

DEMO

Sign up to request clarification or add additional context in comments.

2 Comments

ohh nice one! I will try that. Thank you!
just added proof of concept demo ...without using $sce to inject but does the style trick
0

I'd recommend having all your CSS in an external document and linking to it through the <link> tag

If you want to apply inline CSS to an element you can do it with the style attribute:

<h1 style="color: #0f0;">Tree</h1>

3 Comments

well, the thing is that I am getting that response from an API and I want to show it, so I am afraid that doesn't help. Thanks for the answer anyway.
is there a demo you can provide to test how this content is added dynamically? inline CSS should work regardless, give it a try and let me know what happens
in order to show the content I have to allow it with $sce so I am executing $sce.trustAs($sce.HTML, mystring) and that strips the CSS code from the original string. I tried many things and none worked so I am wondering which is the angularjs way to do this, although I am thinking that the only way for this to work will be to disable $sce, which sucks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.