IFrame Not Being Rendered In ng-bind-html

eat-sleep-code picture eat-sleep-code · Jul 6, 2015 · Viewed 11.2k times · Source

I have a datasource that is used to render blog articles on a page. One of the entries contains an IFRAME. I see the IFRAME being returned in the datasource but it is never rendered to the page in the ng-bind-html.

This is my code:

<div class="blog-post-content" ng-bind-html="entry.content" itemprop="text">
</div>

If I switch this to the following, I see the IFRAME tag rendered out, but of course now it is RAW HTML.

<div class="blog-post-content" itemprop="text">
    {{entry.content}}
</div>

How can I get this IFRAME to be rendered to the page.

Answer

Daniel Beck picture Daniel Beck · Jul 6, 2015

The best approach here is to refactor your data source to only contain the URL, rather than the full iframe tag, and use <iframe ng-src="entry.content"></iframe>.

ng-bind-html isn't working for you because the sanitizer is protecting you from potential XSS attacks.

If you don't control the data source, but trust it completely, you can look into using e.g. scope.trustedContent = $sce.trustAsHtml(entry.content); in your directive, and <div ng-bind-html="trustedContent"></div> in the DOM.

(Not controlling it but trusting it completely is, of course, a contradiction in terms, so you may be better off parsing the data source inside your directive to extract the url, rather than trusting the entire string.)