You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AngularJS中iframe的ng-src无法加载YouTube嵌入链接问题

解决AngularJS中ng-src绑定YouTube iframe无法加载的问题

这个问题的核心原因是AngularJS的安全策略:默认情况下,Angular会将动态生成的URL视为不安全资源——哪怕你的post.src值看起来完全正确,也会被拦截,导致iframe只显示预留空间却加载不出内容。要解决这个问题,你需要用到Angular的$sce(Strict Contextual Escaping)服务,把YouTube的embed URL标记为可信的资源URL。

具体解决步骤:

  1. 在控制器中注入$sce服务
  2. 对每个视频链接进行处理,标记为可信资源
  3. 在HTML中绑定处理后的可信URL到ng-src

修改后的代码示例:

1. 更新控制器代码

// controller
app.controller('videoControl', function($scope, $http, $sce) { // 注入$sce服务
  $http.get("pages/db_section/videos.php")
    .then(function (response) {
      // 遍历所有数据,为每个视频生成可信URL
      $scope.posts = response.data.records.map(post => {
        post.trustedSrc = $sce.trustAsResourceUrl(post.src);
        return post;
      });
    });
});

2. 更新HTML中的iframe部分

<td>
  <iframe width='560' height='315' ng-src='{{ post.trustedSrc }}' frameborder='0' allow='autoplay; encrypted-media' allowfullscreen></iframe>
</td>

额外验证建议:

  • 确认PHP生成的src是标准YouTube embed格式,比如https://www.youtube.com/embed/xxxxxx(你的str_replace逻辑已经完成了watch?v=到embed/的转换,这部分是正确的)
  • 如果数据库中的原始链接没有https://前缀,建议在PHP中补全,避免出现无效URL:
$source = str_replace("watch?v=","embed/",$rs["src"]);
// 补全HTTPS前缀(如果原始链接缺失的话)
if(strpos($source, 'https://') === false && strpos($source, 'http://') === false) {
  $source = 'https://www.youtube.com/embed/' . substr($source, strrpos($source, '/') + 1);
}

这样修改后,Angular就会信任这个视频URL,iframe就能正常加载YouTube内容了。

内容的提问来源于stack exchange,提问作者Al Nafis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:40:04