Skip to content Skip to sidebar Skip to footer

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: Bar When I load the page cont

Solution 1:

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.


Solution 2:

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


Post a Comment for "Ng-click Not Working In Manually Loaded HTML"