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>