Irfan Beganovic Irfan Beganovic - 22 days ago 5
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"
ng-bind-html-unsafe="invoice_html_template"
class="span6"
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;">
</div>


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',
id:$scope.our_company_id
},
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
#invoice_template_preview

Answer

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;
            element.html(template);
            $compile(element.contents())(scope);
        });
    },
    template: '<div>{{$scope.invoiceTemplate}}</div>'
});

and it can be used:

<div id="invoice_template_preview">
    <custom-directive></custom-directive>
</div>

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);