Rendering directives within $sce.trustAsHtml

I’ve included a Plunker here:

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.


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

        $scope.testAlert = function () {


<body ng-controller="MainCtrl">
    <div ng-bind-html="trustedHtml"></div>

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

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.


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

In controller:

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


.directive('initBind', function($compile) {
return {
        restrict: 'A',
        link : function (scope, element, attr) {

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply