Reputation: 14985
From server, I get a complete HTML document similar to the one below as a string
.
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<style>
body {
color: #eeeeee;
}
h1 {
color: red;
}
</style>
</head>
<body>
<section>
<h1>Header</h1>
<p>This is a pargraph</p>
</section>
</body>
</html>
In angularJS, how to compile this string into an HTML
document and then display it inside an another one?
Upvotes: 0
Views: 430
Reputation: 196
You can simply use the ngBindHtml directive.
To know in breif about how to use ngBindHtml directive refer https://docs.angularjs.org/api/ng/directive/ngBindHtml
Below is an example which uses ngBindHtml directive and renders the HTML
(function(){
angular
.module('myApp',['ngSanitize'])
.controller('myCtrl', Controller);
Controller.$inject = ['$rootScope', '$scope'];
function Controller($rootScope, $scope){
activate();
function activate(){
$scope.html = "<h1>Header</h1><p>This is a pargraph</p>";
}
}
})();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Demo</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-sanitize.js"></script>
<div
ng-app="myApp"
ng-controller="myCtrl">
<div ng-bind-html="html"></div>
</div>
</body>
</html>
Upvotes: 0
Reputation: 41
I have done this before using the $compile angular service and directives.
You can reference it at https://docs.angularjs.org/api/ng/service/$compile
Here you have some code example
app.directive("example", function($compile){
return{
link: function(scope, element){
var t = "<button ng-click='printSomething()'>{{label}}</button>";
var compFn = $compile(t);
var content = compFn(scope);
element.append(content);
}
}
});
Than you can pass the html string to the directive as:
Instead of var t = "<button ng-click='printSomething()'>{{label}}
you could pass the html string within your $scope such as
app.directive("example", function($compile){
return{
restrict:'E',
scope: {
htmlString: '=htmlString'
},
link: function(scope, element){
var compFn = $compile(scope.htmlString);
var content = compFn(scope);
element.append(content);
}
}
});
Than your html file content would be:
<example html-string="{{htmlString}}"></example>
You can also find good guideline for implementing directives in the angular documentation at Angular Directives Documentation
Upvotes: 1