不能通过AngularJS控制器网址加载到iframe中 [英] Unable to load url into iframe via AngularJS controller

查看:190
本文介绍了不能通过AngularJS控制器网址加载到iframe中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个URL动态加载到通过AngularJS iframe中。出于某种原因,我不能在这个小提琴。有人可以告诉我,我做错了什么?为什么我不能绑定到我的控制器设置网址?在code是pretty小:

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';
}

感谢您!

推荐答案

这是您的code不工作的原因是因为源不被信任。为了获得源代码被信任,就需要使用 $ SCE 服务作为<一个href=\"http://stackoverflow.com/questions/20045150/angular-js-how-to-set-an-iframe-src-attribute-from-a-variable\">recommended在这个岗位。如果你这样做,你结束了以下内容:

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>

控制器

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

请参阅更新的提琴: http://jsfiddle.net/W4WyL/4/

修改 - 我原来的答复表示,以去除大括号内。这是完全不正确。花括号中需要 NG-SRC 以有实际的URL进行评估。之所以这样的显得的工作是因为code是模板的一部分被隐式信任,而变量都没有。这就是说,网址是绝对无效的 - 它只是试图加载当前页面内的变量的名称。希望这将有助于其他人在未来的尝试删除大括号!

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!

这篇关于不能通过AngularJS控制器网址加载到iframe中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆