最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Unable to load url into iframe via AngularJS controller - Stack Overflow

programmeradmin2浏览0评论

I'm trying to dynamically load a URL into an iframe via AngularJS. For some reason, I cannot as shown in this fiddle. Can someone please tell me what I'm doing wrong? Why can't I bind to a URL set in my controller? The code is pretty small:

<div ng-app ng-controller="LoginController">
    <div>Trying to load {{ customUrl }}</div>
    <div><iframe ng-src="{{trustSrc(customUrl)}}" height="480" width="640"></iframe></div>
</div>

function LoginController($scope) {
    $scope.customUrl = '';
}

Thank you!

I'm trying to dynamically load a URL into an iframe via AngularJS. For some reason, I cannot as shown in this fiddle. Can someone please tell me what I'm doing wrong? Why can't I bind to a URL set in my controller? The code is pretty small:

<div ng-app ng-controller="LoginController">
    <div>Trying to load {{ customUrl }}</div>
    <div><iframe ng-src="{{trustSrc(customUrl)}}" height="480" width="640"></iframe></div>
</div>

function LoginController($scope) {
    $scope.customUrl = 'http://www.google./custom';
}

Thank you!

Share Improve this question asked Jul 8, 2014 at 14:49 user3284007user3284007 1,7177 gold badges30 silver badges44 bronze badges 1
  • maybe what you are looking for: stackoverflow./questions/20045150/… – Raphael Müller Commented Jul 8, 2014 at 14:53
Add a ment  | 

1 Answer 1

Reset to default 10

The reason that your code isn't working is because the source isn't trusted. In order to get the source to be trusted, you need to use the $sce service as remended in this post. If you do that you end up with the following:

Html

<div><iframe ng-src="{{customUrl}}" height="480" width="640"></iframe></div>

Controller

function LoginController($scope, $sce) {
    $scope.customUrl = $sce.trustAsResourceUrl('http://www.cnn.');   
}

See the updated fiddle: http://jsfiddle/W4WyL/4/

Edit - My original answer said to remove the curly braces. This was pletely incorrect. The curly braces are required in ng-src in order to have the url actually be evaluated. The reason this seemed to work is because code that is part of the template is implicitly trusted while variables are not. That said, the url was absolutely not valid - it just tried to load the name of the variable inside of the current page. Hopefully this will help others in the future that try removing the curly braces!

发布评论

评论列表(0)

  1. 暂无评论