1

In this plunk I have an HTML table in a variable. I render the table with ng-bind-html and that works fine. The problem is that I cannot trigger events when cells are clicked. For example, ng-click at the cell level doesn't call functions declared in AngularJS. How to capture the clicks?

HTML

<div ng-bind-html="html"></div>

Javascript

var app = angular.module('app', []);
app.controller('ctl', function ($scope,$sce) {

          var htmlTable = `
            <table border="1">
                <tr>
                    <td ng-click="clicked()">
                        $39,431.67
                    </td>
                    <td ng-click="clicked()">
                        $14,861.50
                    </td>
                    <td ng-click="clicked()">
                        $7,848.97
                    </td>
                    <td ng-click="clicked()">
                        $16,721.20
                    </td>
                </tr>
        </table> `;

        $scope.html = $sce.trustAsHtml(htmlTable);

    $scope.clicked = function(){
         alert("cell was clicked"); 
    };   
});
ps0604
  • 1,227
  • 23
  • 133
  • 330

1 Answers1

1

You need to create a directive with compile to do the job, take a look at this answer

.directive('compile', ['$compile', function ($compile) {
    return function(scope, element, attrs) {
        scope.$watch(
            function(scope) {
                // watch the 'compile' expression for changes
                return scope.$eval(attrs.compile);
            },
            function(value) {
                // when the 'compile' expression changes
                // assign it into the current DOM
                element.html(value);

                // compile the new DOM and link it to the current
                // scope.
                // NOTE: we only compile .childNodes so that
                // we don't get into infinite loop compiling ourselves
                $compile(element.contents())(scope);
            }
        );
    };
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396