在AngularJS中嵌入Youtube视频会在加载页面时产生错误

时间:2015-02-02 08:25:28

标签: javascript angularjs iframe youtube

下面的代码段用于在我的页面中嵌入Youtube视频。

<div ng-if="videoUrl != ''" style="height:400px;">
    <iframe width="100%" height="100%" src="{{videoUrl}}"></iframe>
</div>

在我的控制器中,videoUrl首先设置为空字符串,并在从服务器检索数据后更新。

$scope.videoUrl = '';

videoService.getData().then(function(response) {
    $scope.videoUrl = response.videoUrl;
});

Youtube播放器工作且URL正确,我可以在页面完全加载后使用嵌入式播放器观看视频。困扰我的是每次加载页面时都会返回错误。我可以在浏览器控制台中看到它正在尝试向GET发送http://www.example.com/%7B%7BvideoUrl%7D%7D请求,其状态为(canceled)。这个请求不是我想要的,它肯定是失败的。

如何摆脱那种奇怪的GET请求?

1 个答案:

答案 0 :(得分:1)

我根据RGraham的建议修改了我的代码,错误现在消失了。

首先,将src更改为ng-src,将检查条件更改为ng-if="videoUrl"

<div ng-if="videoUrl" style="height:400px;">
    <iframe width="100%" height="100%" ng-src="{{videoUrl}}"></iframe>
</div>

其次,我将videoUrl初始化为undefined

$scope.videoUrl = undefined;

现在页面加载时不再发送上一个奇怪的GET请求。

相关问题