How to show mixed html and css with angularJS


Tags: html,css,angularjs

Problem :

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?



Solution :

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


    CSS Howto..

    How can I override an external css?

    how to make menu on mouse hover in CSS

    How do I set image src based on li active status?

    How to fade loop background images?

    How to keep footer at the bottom even with dynamic height website

    How to blur one side of the div using CSS

    How to make tabs with pure HTML/CSS

    How to create a menu 'toolbar' like on the default Google homepage?

    How to specify the system’s default serif and sans-serif font-family?

    How to generate a elongated hexagon shape with two circular sides?

    JavaScript: How to clear my custom keyboard mappings and use the default ones

    How to adjust button css styles

    How to avoid text go below the thumbnail with css

    How to create Curved & Overlapping Menu Tabs in CSS

    How to use active and before with CSS?

    How to assign color obtained by CSS gradient generator

    How to use weather API to create my weather HTML page [closed]

    CKEditor 4: How to add CSS stylesheet from plugin?

    How to position AdSense on site with CSS position: absolute

    HTML/CSS: How to use another font for list-item Bullets

    How can I use jQuery to hide or show table rows based on asp.net role?

    How to avoid the text inside the bootstrap button overflow?

    Keeping content “fixed” under slideshow of different image sizes

    How to inject css in another page

    How to get rid of an automatically generated span via CSS (un-display)?

    In Jquery how to add Css?

    Greasemonkey how to apply a CSS rule only for @media print?

    My sidebar is not going to right of my page, but to my left. How do I fix this?

    How to use scaleable pixels in css

    how can i center a nested div