Inserting pure HTML with styles and JS in Angular app can be very useful. Sometimes it is needed to pass rendered HTML code from the backend and insert it to frontend but the common problem is that this code is not rendered and compiled so most likely it will be without styles - only plain HTML.
This is happening because the DOM is already rendered and new inserted HTML code will note be re-render.
To prevent this we will use $compile
method.
So let's say that we have rendered HTML data passed in JSON object:
$scope.HTMLcode = '<md-content md-theme="docs-dark" layout-gt-sm="row" layout-padding> <div> <md-input-container> <label>Title</label> <input ng-model="user.title"> </md-input-container> <md-input-container> <label>Email</label> <input ng-model="user.email" type="email"> </md-input-container> </div> </md-content>';
And in our HTML template we have this:
<div ng-bind-html="HTMLcode"></div>
The first problem will be that input elements were not rendered. This is because we have to create filter which will mark this html code s trusted:
app.filter("trust", ['$sce', function($sce) {
return function(htmlCode){
return $sce.trustAsHtml(htmlCode);
}
}]);
So, now we can apply this filter to our HTML code:
<div ng-bind-html="HTMLcode | trust"></div>
Now we can see that our input elements are rendered but without any styles. So somehow we have to compile this piece of code and update our scope.The best route to go in this case is using $compile method and put it into directive:
app.directive('compileHtml', function($compile) {
return {
restrict: 'AE',
link : function (scope, element, attr) {
attr.$observe('ngBindHtml',function(){
if(attr.ngBindHtml){
$compile(element[0].children)(scope);
}
})
}
};
});
And now we can apply this directive to our rendered HTML code:
<div ng-bind-html="HTMLcode | trust" compile-html></div>
and our HTML will be rendered and compiled - all css styles and JS added in our code should work.
usefull link: