insert an iframe into page dynamically in AngularJS
Asked Answered
V

3

22

I am trying to dynamically insert an iframe into a page with Angular 1.2. Here is the code:

html:

<div id="player_wrapper" ng-cloak>
    <div ng-bind-html="player"></div>
</div>

js:

$http({method: 'GET', url: url}).
    success(function(data, status) {
        $scope.player = data.html;
    }.......

So the data.html is a string that has a valid HTML starting with

<iframe ...>

The string contains also some div. So it could look like:

<iframe src='...' ...></iframe><div>some stuf</div>

I use in app.js 'ngSanitize'. What it shows is the div (after the iframe) but not the iframe itself.

If I use jQuery, basically a

$(#'player_wrapper').html(data.html)

works fine... but trying to make it proper angularJS.

Any idea on why only the divs after the iframe are being displayed?

Many thanks all

Valorie answered 23/11, 2013 at 17:51 Comment(2)
Can you try using ng-include.Dvinsk
tried this:<div ng-include="player"></div> and get an error XMLHttpRequest (I'm developing locally so I have a file:// in url...)Valorie
K
34

ngBindHtml will pass your HTML through $sce.getTrustedHtml before displaying it. I suspect this is what would be removing your iframe.

According to the docs you can use $sce.trustAsHtml to avoid this check so long as you fully trust any HTML coming from this source - an iframe from an untrusted source could likely do a number on nasty things to visitors to your page.

$http({method: 'GET', url: url}).
    success(function(data, status) {
        $scope.player = $sce.trustAsHtml(data.html);
    }.......

Be careful! :)

Karlie answered 23/11, 2013 at 19:30 Comment(0)
F
8

You need to use the $sce service as desribed in the documentation of ng-bind-html:

$scope.player = $sce.trustAsHtml('your html goes here');

See this plunk for an example:

Filberte answered 23/11, 2013 at 19:40 Comment(0)
S
4

After much trouble I managed to get a nice setup going where I can dynamically load iframes into my page and pass information through to it.

I made this a github project. It uses a single directive for passing raw input element information, and also uses ngSanatize for the $sce.trustAsResourceUrl function.

Here is the live demo

Sitdown answered 3/7, 2014 at 19:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.