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

1 Answer 1

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);
            }
        );
    };
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.