0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

That's an interesting approach, how would you use this in the html? As an attribute to a div?
Figured it out, you literally just replace one call with the other. Awesome solution, thanks!
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.