keybored
keybored

Reputation: 5248

ng-click not working in manually loaded HTML

I have a JSON file that contains the page content I wish to load. In it, I have a link that looks like this:

<a data-ng-click='foo()'>Bar</a>

When I load the page content into the page as HTML:

<p class="body" ng-bind-html="jsonText | raw"></p>

using this filter:

app.filter('raw', function ($sce) {
    return function (input) {
        return $sce.trustAsHtml(input);
    }
});

the link does not trigger foo() call on click. Is what I'm trying to do impossible or am I doing something wrong?

Upvotes: 0

Views: 189

Answers (2)

hon2a
hon2a

Reputation: 7214

Using filter for this is not a good idea, because you need to $compile the loaded HTML and for that you need $scope. So, you either need to $compile it manually and put the result in $scope yourself, or create a directive instead of a filter:

.directive('dynamicHtml', ['$compile', function ($compile) {
    return {
        link: function ($scope, $element, $attrs) {
            $scope.$watch($attrs.dynamicHtml, function (html) {
                $element.empty().append($compile(html)($scope));
            });
        }
    };
}]);

and use it instead of ngBindHtml:

<p dynamic-html="jsonText"></p>

Just be aware that by compiling the HTML yourself, you're completely bypassing contextual escaping, so you should only do it with your own, secure content.

Upvotes: 2

ppoliani
ppoliani

Reputation: 4906

The problem is that your adding a plain text into DOM. Your filter will just ad an piece of html text which includes the ng-click directive which as far as the browser is concerned, it is just an attribute it cannot understand.

You need to compile the template using the $compile service before injecting it into the dom

Upvotes: 2

Related Questions