Rendering directives within $sce.trustAsHtml

20,273

Solution 1

$sce.trustAsHtml and ng-bind-html are not meant to build HTML with directives. This technique will not work.

This is because angular works by first compiling and then linking. See the conceptual overview for a good explaination.

In short, by the time you link the HTML defined in your trustAsHtml, it is too late for angular to compile (and therefore understand) the ng-click directive.

In order to dynamically add HTML, you should be looking at the $compile service (and/or directives). Docs are here.

Solution 2

For Angular 1.6.1, I found a solution that worked for me.

template:

<div ng-bind-html="trustAsHtml(content);" init-bind> </div>

In controller:

    $scope.trustAsHtml = function(string) {
        return $sce.trustAsHtml(string);
    };

Directive:

.directive('initBind', function($compile) {
return {
        restrict: 'A',
        link : function (scope, element, attr) {
            attr.$observe('ngBindHtml',function(){
                if(attr.ngBindHtml){
                     $compile(element[0].children)(scope);
                }
            })
        }
    };
})
Share:
20,273

Related videos on Youtube

rjm226
Author by

rjm226

Updated on February 02, 2020

Comments

  • rjm226
    rjm226 over 4 years

    I've included a Plunker here: http://plnkr.co/edit/4vqV8toHo0vNjtfICtzI?p=preview

    I'm trying to add a button to the DOM and when clicked should execute the function bound to it. In this case it should alert "testing". Here is the code.

    controller

    app.controller('MainCtrl', function($scope, $sce) {
            $scope.trustedHtml = $sce.trustAsHtml('<button ng-click="testAlert()">Submit</button>');  
    
            $scope.testAlert = function () {
                alert('testing')
            };
    });
    

    HTML

    <body ng-controller="MainCtrl">
        <div ng-bind-html="trustedHtml"></div>
    </body>
    
  • rjm226
    rjm226 over 10 years
    Right, Here's a new plunker showing how this was achieved with $compile. plnkr.co/edit/3CewDscih8diAo4mMSwJ?p=preview Here are some other resources that helped me solve this: stackoverflow.com/questions/18157305/…
  • AnxiousdeV
    AnxiousdeV about 10 years
    Is this possible when building a row in a table and injecting html that contains the keyword dynamic directive?
  • Daniel Darabos
    Daniel Darabos almost 9 years
    I wish you showed how to solve the problem specifically.
  • rajesh_kw
    rajesh_kw over 7 years
    This also is a solution if anyone willing to try.
  • Vippy
    Vippy over 6 years
    BRILLIANT! Great use of directives and $compile. Thank you!