"Creating Stylish Angular HTML Previews with Customized CSS

I am currently in the process of developing an application using AngularJS that includes a feature to display an HTML preview directly after the user has written the HTML in a textarea. However, I am facing a challenge on how to isolate the CSS for the HTML itself when the user inputs styles in the textarea. It is important that the HTML CSS in the preview does not override the main CSS of the application.

Below is a snippet of my code:

Directive to display the HTML preview :

app.directive('htmlViewer', ['$sce', function($sce){
  return {
    scope: {
      htmlViewer: '=',
    },
    template: "<div ng-bind-html='trustedHtml'></div>",
    link: function($scope, iElm, iAttrs, controller) {
      $scope.updateView = function() {
        $scope.trustedHtml = $sce.trustAsHtml($scope.htmlViewer);
      }

      $scope.$watch('htmlViewer', function(newVal, oldVal) {
        $scope.updateView(newVal);
      });
    }
  };
}]);

And here is how the view looks like :

<div html-viewer="myHtmlModel.content"></div>

Could you please provide some guidance on how to implement this feature? I want to ensure that the HTML preview and its CSS do not override the main app's CSS. Please note that I am relatively new to Angular.

EDIT Here is a sample of the HTML in the textarea:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta name="viewport" content="width=device-width" />
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Template</title>
        <style>

        /* -------------------------------------
        GLOBAL
        ------------------------------------- */
        body {
         -webkit-font-smoothing: antialiased;
         -webkit-text-size-adjust: none;
         width: 100%;
         min-width:300px;
         max-width:680px;
         margin:0 auto;
         height: 100%;
         background:#f6f6f6!important;
        }


        </style>
    </head>

    <body bgcolor="#f6f6f6">

       <!-- content -->
         <div class="content">
             Lorem ipsum dolor sit amet
         </div>
       <!-- /content --> 
     </body>
  </html>

Your help or suggestions would be greatly appreciated.

Thank you.

SOLUTION

In the end, I opted to utilize an iframe to address this issue. By creating a new directive and combining it with the previous one.

app.directive('framePreview', function($compile) {
  return function($scope, $element) {
    var $body = angular.element($element[0].contentDocument.body),
        template  = $compile('<div html-viewer="myHtmlModel.content"></div>')($scope);
    $body.append(template);
  };
});

Then, in my view:

<iframe frame-preview="" width="100%" height="500px"></iframe>

Answer №1

Perhaps considering the option of using an iframe instead could be beneficial? Platforms such as jsFiddle and jsBin utilize iframes for code preview functionalities.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Prevent the Bootstrap Navbar from collapsing

Trying to customize a Bootstrap navbar for specific needs, I've encountered an issue. I want the first two links on the left (home and menu glyphs) to remain visible even when the window is resized down, while the rest should collapse. Check out the ...

Tips for accessing global variables in an Angular 2 Component

How can I access the Google API library from an Angular 2 module written in Typescript? Whenever I try to access (gapi), it returns undefined. Is there an NPM module available that functions as a Typescript library in Angular 2, or do I need to use the Jav ...

Trouble locating Angular module while referencing script as an ES6 module

Check out this simple plunk here. My goal is to reference the app.js file as an ES6 module by setting the type attribute of the script tag to module. However, when I add the type attribute, Angular is unable to find the module. If I remove it, then it work ...

The relationship between a CSS parent and child elements

Currently, I have successfully included my form within <ul><li> tags, functioning well with label and form elements. The CSS code for the form is straightforward and requires no explanation: #form ul {....} #form ul li {....} Now, my dilemma ...

Drupal-add-css is acting non-responsive

When incorporating javascript and css into my project, I am encountering an issue. Here is the code snippet I am using: if( $form['#node']->type == 'e_form' ){ drupal_add_css( drupal_get_path('module', 'e_form&apo ...

What is the proper way to retrieve this stylesheet and add it to the header of my HTML file?

I want to utilize a style sheet from Wikipedia. However, when I fetch the style sheet and attempt to pass the URL retrieved through AJAX to the head of my HTML document, the URL behaves unexpectedly. Initially, I tried to use the fetched URL directly: var ...

Center-align the table element

I've been struggling to center align this table element, specifically the one containing the square, but nothing seems to be working. Can anyone lend a hand in fixing this issue? <table> <tbody> <tr> <td>TURKEY - SU ...

Apply a dual-color gradient background vertically

I am trying to figure out how to achieve a two-tone background color in an HTML document. I know this question has been asked before, but I specifically want the colors to be split vertically rather than horizontally. ...

Is there a method in AngularJS to have $http.post send request parameters rather than JSON?

I have come across some older code that utilizes an AJAX POST request using jQuery's post method. The code looks something like this: $.post("/foo/bar", requestData, function(responseData) { //do stuff with response } The request ...

Enhance the organization of your current webpage by incorporating three divs positioned side by side

I currently have a webpage set up, accessible here: https://plnkr.co/edit/5NWm4E868nXYyixd2SLv?p=preview The current layout looks okay, but I feel restricted in terms of customization. Therefore, I am interested in creating 3 divs where I can have more co ...

Achieving perfect alignment both horizontally and vertically using CSS3's viewport height of 100%

I'm trying to utilize CSS3's Viewport Height to create a fullscreen section with a height of 100vh. However, I am encountering difficulties in centering elements both horizontally and vertically within the section. My goal is to have an image and ...

The font is not displaying properly in any browser, even though everything appears to be set up

Despite reading through all the relevant answers on various platforms, I am still unable to display my fonts properly. I have checked the paths, ensured that the files are in the correct location, and even tested a font squirrel example, but to no avail. ...

Using AngularJS to establish a connection with a remote server

I am working with a secure Restful API (localhost:8180) that requires authentication. I am using Angular JS HTTP services to log in to the server and retrieve data from localhost:8180/api/version/?1 (just an example). Below is the code snippet: //Config ...

What is the CSS technique for concealing the content of an ordered list item while retaining the marker?

In our order process, we utilize an ordered list to display the steps in sequence: <ol> <li>Products</li> <li class="active">Customer</li> <li>Payment</li> </ol> On desktop view, it appears a ...

Exploring Options for Enabling HTML in AngularUI Accordion-Group Content

I want to showcase content in an accordion-group that might contain HTML markup. This content is fetched from external sources. How can I achieve this? You can check out an example at Plnkr (content hard-coded for testing) Currently, the items are displa ...

Modifying CSS stylesheet does not alter the background color

body { background-color: bisque; } <!DOCTYPE html> <html> <head> <title>Reading</title> </head> <body> <h1> <button><a href="index.html">Home</a></button> & ...

What is the reason behind Object.hasOwn(x,y) being different from Reflect.ownKeys(x).includes(y) when x represents a CSSStyleDeclaration object and y is a hyphenated property such as 'z-index'?

Both of these conditions are true: 'z-index' in getComputedStyle(document.body) // true Reflect.has(getComputedStyle(document.body), 'z-index') // true Additionally, the following statements also evaluate to true, indicating that &apo ...

Upgrade angular-chart.js when applied to a filtered collection

I recently started working with Angular and encountered an issue while incorporating Angular Charts JS. I have a list that can be filtered using search text, and I want my charts to update whenever the list is filtered. What would be the best approach to ...

moment js struggling with correctly interpreting the date format in a Japanese locale

I am having trouble translating the date format to Japanese locale as the output is incorrect. I have attempted to change the browser's locale settings, but it doesn't seem to be working in both Chrome and IE. app.filter('japan', funct ...

Creating stylish horizontal stripes in a table using CSS

I've been attempting to assign a unique color to every nth row, but my efforts with the :nth-child property are affecting columns instead of rows. Despite trying various solutions and scouring the internet for answers, I have yet to find a successful ...