AngularJS 使用 angularjs 的时候,在 iframe 里面无法正确显示 src 指定的内容,

msms · May 21, 2014 · Last by lyfi2003 replied at May 22, 2014 · 28416 hits

在做页面的时候,会在页面上显示别的网站的内容、图片或者视频一类的,我想使用 iframe 来简单的实现这个功能, 不过在使用以下代码:

HTML 代码:

<div ng-show="paragraph.show">
    <span ng-click="addModify(paragraph)" class="glyphicon glyphicon-plus"></span>
</div>
<div ng-show="!paragraph.show">
    <div class="input-group">
        <div class="input-group-addon">
            <span class="glyphicon glyphicon-globe" ng-click="addModify(paragraph)"></span>
        </div>
        <input ng-model="paragraph.modifyURL" type="text" class="form-control" placeholder="Please input the URL.">
    </div>
    <div class="">
        <p>{{paragraph.modifyURL}}</p>
        <iframe width="100%" height="100%" seamless frameborder="0" ng-src="{{trustSrc(paragraph.modifyURL)}}" ></iframe>
    </div>
</div>

JS 代码

$scope.trustSrc = (url) ->
  $sce.trustAsResourceUrl(url)

$scope.addModify = (paragraph) ->
  paragraph.show = !paragraph.show

结果当我在 input 里面输入 www.baidu.com 的时候, 报错: No route matches [GET] "/show/www.baidu.com"

这个有人知道是为什么,,,

这应该是好使的,只是你的 URL 写错了:

试试

<iframe width="100%" height="100%" seamless frameborder="0" ng-src="/{{trustSrc(paragraph.modifyURL)}}" ></iframe>

在前 ng-src 前加一个 / 号。

#1 楼 @lyfi2003 加一个 / 号会让 ng-src 无法正确找到 input 里面输入的值,,,

#2 楼 @Msms 那就你改到 controller 试试:

$scope.trustSrc = (url) ->
  "/" + $sce.trustAsResourceUrl(url)

#1 楼 @lyfi2003 不过用了别的方法可以搞定,从错误信息来看,每次 ng-src 变化的时候,会向服务器请求这个地址,就在 rails 里面让服务重新请求一下,,

#3 楼 @lyfi2003 不知道为什么非要向服务器请求一次,,,

那你把完整的地址加上 http://

#7 楼 @lyfi2003 加了之后生成 iframe 更加诡异了

src 标签没有了,,,

<iframe width="100%" height="100%" seamless="" frameborder="0">
<html><head></head><body></body></html>
</iframe>
$scope.trustSrc = (url) ->
  "http://" + $sce.trustAsResourceUrl(url)

#9 楼 @Msms 加里面试试

#10 楼 @lyfi2003 搞定

$scope.trustSrc = (url) ->
  $sce.trustAsResourceUrl("http://" + url)

#10 楼 @lyfi2003 可以解释下为什么麼,对 angularjs 上周末刚开始看,,,

#12 楼 @Msms URL 首先区分绝对与相对路径,之前你是相对路径,访问时加了 /show/xxx, 这肯定不对,我以为你需要绝对路径,所以建议你加上 /, 后面发现不是。

你需要的是完整路径,所以就按最后的方案解决就可以了。

trustAsResourceUrlAngularjs 防止用户注入 URL, 而设计的安全需求,了解即可。

#13 楼 @lyfi2003 嗯,学习了,加上 "/" ,会从网站的根目录请求,加上"http://" 就会请求完整的地址, 以前只有在服务器端考虑相对路径的问题,,, 谢谢!!

You need to Sign in before reply, if you don't have an account, please Sign up first.