Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

javascript - Unable to load url into iframe via AngularJS controller

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.com/custom';
}

Thank you!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 recommended 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.com');   
}

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

Edit - My original answer said to remove the curly braces. This was completely 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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...