Ng-click not working in manually loaded HTML

I have a JSON file that contains the content of a page that I want to download. In it I have a link that looks like this:

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

      

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

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

      

with this filter:

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

      

the link does not trigger a call foo()

when clicked. Am I trying to make it impossible or am I doing something wrong?

0


source to share


2 answers


Using a filter for this is not a good idea because you need the $compile

HTML loaded and for that you need $scope

. So you either need $compile

it manually, or 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 ngBindHtml

:



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

      

Just remember that by compiling the HTML yourself, you completely bypass context escaping , so you should only do this with your own, protected content.

+2


source


The problem is you are adding plain text to the DOM. Your filter will simply declare a piece of html text that includes the ng-click directive that touches the browser, this is just an attribute that it cannot understand.



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

+2


source







All Articles