Irfan Beganovic Irfan Beganovic - 2 years ago 233
AngularJS Question

Angular: append html in dom element

I need to write directive to append html in div

Here i want to append html which i get it from server usinh $http post request

<div id="invoice_template_preview"
style="background: rgba(242, 230, 205, 0.95);margin: -100px 0 0 0;border: 1px solid #ddd; height: auto;padding: 18px;position: relative;width: 50% !important;">

This is my angular function to get html from db

$scope.getInvoiceTemplate = function() {

$scope.invoiceTemplate = [];

var request = $http({
method: "post",
url: "/c_make_invoice/",
data: {
action: 'getInvoiceTemplate',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }

request.success(function (data) {
$scope.invoiceTemplate = data.result;
$scope.invoice_html_template = $scope.invoiceTemplate.invoice_html_template;
$scope.invoice_num_format = $scope.invoiceTemplate.invoice_num_format;

I try this

$scope.invoice_html_template = $scope.invoiceTemplate.invoice_html_template;

but its not a proper way to solve this.

I return json from server, how i can append that html in

Answer Source

Updated directive to watch the scope variable. When it changes the template html is changed to whatever is in the variable.

.directive('CustomDirective', function(){
    return {
    restrict:  'E',
    link: function(scope, element, attrs){
        scope.$watch('invoice_html_template', function(){
            var template = scope.invoice_html_template;
    template: '<div>{{$scope.invoiceTemplate}}</div>'

and it can be used:

<div id="invoice_template_preview">

You should also be using $sce when getting hold of the HTML. see sce

request.success(function (data) {
    $scope.invoiceTemplate = $sce.trustAsHtml(data.result.invoice_html_template);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download