Amit Mishra
Amit Mishra

Reputation: 69

IFrame In AngularJS

I want to bind iframe in a div that is returning by my database,

<iframe width=&quot;560&quot; height=&quot;315&quot; src=&quot;https://www.youtube.com/embed/zvo9m_e8ekA&; frameborder=&quot;0&quot; allow=&quot;autoplay; encrypted-media&quot; allowfullscreen></iframe>

Is this possible to bind in following div

<div ng-app="myApp" ng-controller="dummy">

Upvotes: 0

Views: 94

Answers (2)

Protozoid
Protozoid

Reputation: 1207

You will need to use the $sce service in conjunction with ng-bind-html in order to parse the string as safe HTML.

If your string is: "<iframe width=&quot;560&quot; height=&quot;315&quot; src=&quot;https://www.youtube.com/embed/zvo9m_e8ekA&; frameborder=&quot;0&quot; allow=&quot;autoplay; encrypted-media&quot; allowfullscreen></iframe>"

Then you need to replace the &quot; with apostrophes and then parse it as safe HTML, as such:

dummy.unsafeIframeCode = "<iframe width=&quot;560&quot; height=&quot;315&quot; src=&quot;https://www.youtube.com/embed/zvo9m_e8ekA&; frameborder=&quot;0&quot; allow=&quot;autoplay; encrypted-media&quot; allowfullscreen></iframe>";

dummy.unsafeParsedIframeCode = dummy.unsafeIframeCode.replace(/\&quot\;/gi, "'");

dummy.safeIframeCode = $sce.trustAsHtml(dummy.unsafeParsedIframeCode);

And simply bind it in HTML as such:

<div ng-app="myApp" ng-controller="dummy" ng-bind-html="dummy.safeIframeCode">

Full working JSFiddle here

Upvotes: 1

chinmayan
chinmayan

Reputation: 1384

ng-bind-html willn't work for binding your iFrame, because the sanitizer is protecting your app from potential XSS attacks.

If you trust/control the data source completely, you can look into using trustAsHtml e.g. scope.trustedData = $sce.trustAsHtml(content); in your directive controller(where content is your iFrame "<iframe.../>"), and <div ng-bind-html="trustedData"></div> in the DOM. It'll do the task for you.

Upvotes: 0

Related Questions