Sajeetharan Sajeetharan - 3 months ago 8
AngularJS Question

Load an URL inside an iFrame in AngularJS app

I am loading a url in an angular application inside an iframe. Here is my code:

HTML:

<div layout="column" flex class="content-wrapper" id="primary-col">
<md-content layout="column" flex class="md-padding">
<h2>{{selected.name}}</h2>
<p>{{selected.content}}</p>
<div class="cell">
<iframe ng-src="{{selected.imgurl}}" >
</div>
</md-content>
</div>


App.Js:

var routerApp =angular.module('DiginRt', ['ngMaterial'])
routerApp.controller('AppCtrl', ['$scope', '$mdSidenav', 'muppetService', '$timeout','$log', function($scope, $mdSidenav, muppetService, $timeout, $log) {
var allMuppets = [];

$scope.selected = null;
$scope.muppets = allMuppets;
$scope.selectMuppet = selectMuppet;
$scope.toggleSidenav = toggleSidenav;

loadMuppets();

//*******************
// Internal Methods
//*******************
function loadMuppets() {
muppetService.loadAll()
.then(function(muppets){
allMuppets = muppets;
$scope.muppets = [].concat(muppets);
$scope.selected = $scope.muppets[0];
})
}

function toggleSidenav(name) {
$mdSidenav(name).toggle();
}

function selectMuppet(muppet) {
$scope.selected = angular.isNumber(muppet) ? $scope.muppets[muppet] : muppet;
$scope.toggleSidenav('left');
}
}])

routerApp.service('muppetService', ['$q', function($q) {
var muppets = [{
name: 'Product Report',
iconurl: 'https://lh3.googleusercontent.com/-KGsfSssKoEU/AAAAAAAAAAI/AAAAAAAAAC4/j_0iL_6y3dE/s96-c-k-no/photo.jpg',
imgurl: 'https://my.infocaptor.com/dash/mt.php?pa=inflation_50da569f84101',
content: ' '
}, {
name: 'Invoice Report',
iconurl: 'https://yt3.ggpht.com/-cEjxni3_Jig/AAAAAAAAAAI/AAAAAAAAAAA/cMW2NEAUf-k/s88-c-k-no/photo.jpg',
imgurl: 'https://my.infocaptor.com/dash/mt.php?pa=inflation_50da569f84101',
content: ''
} ];

// Promise-based API
return {
loadAll: function() {
// Simulate async nature of real remote calls
return $q.when(muppets);
}
};
}]);


It rerurns an error saying
Error: [$interpolate:interr] Can't interpolate: {{selected.imgurl}}
Error: [$sce:insecurl] Blocked loading resource from url not allowed by $sceDelegate policy.


Here is the
Plunker

Answer

You need to sanitize URL using $sce API, by using that you need to make that URL as trusted by calling method trustAsResourceUrl.

Method

$scope.trustSrc = $sce.trustAsResourceUrl;

HTML

<iframe ng-src="{{trustSrc(selected.imgurl)}}"></iframe>

Don't forget to add $sce dependency on your controller.

Working Plunkr with you code

Hope this could help you. Thanks.

Comments