所以我有一个页面,我需要在iFrame中嵌入一个youtube预告片,根据视图中点击的电影/系列。为此,我使用Youtube Search API。
现在加载页面时,它首先从另一个API获取一些数据,加载Youtube API,然后获取预告片的videoId,并将其分配给视图中的$scope
变量。 / p>
在视图中我得到了一些代码:
<div class="row">
<iframe width="420" height="315" ng-src="{{video}}" frameborder="0" allowfullscreen></iframe>
</div>
控制器看起来像这样:
var serieId = $routeParams.id;
$http.get("http://api.tvmaze.com/shows/" + serieId)
.success(function (data) {
console.log(data);
$scope.name = data.name;
$scope.img = data.image.medium;
$scope.rating = data.rating;
initYTAPI();
$http.get("http://api.tvmaze.com/shows/" + serieId + "/episodes")
.success(function (episodes) {
console.log(episodes);
$scope.episodes = episodes;
var maxSeason = 0;
for (var i = 0; i < episodes.length; i++) {
if (episodes[i].season > maxSeason) {
maxSeason = episodes[i].season
}
}
$scope.seasonCount = [];
for (var i = 1; i <= maxSeason; i++) {
$scope.seasonCount.push(i)
}
});
});
initYTAPI函数:
gapi.client.setApiKey("MY_API_KEY");
gapi.client.load("youtube", "v3", function(){
//yt api is ready
console.log("Api ready");
var query = $scope.name + " Official Trailer";
var request = gapi.client.youtube.search.list({
part: "snippet",
type: "video",
q: query,
maxResults: 1
});
request.execute(function(response){
var base_URL = "https://www.youtube.com/embed/";
var url = base_URL + response.items[0].id.videoId;
url = $sce.trustAs($sce.RESOURCE_URL, url);
console.log(url);
$scope.video = url;
//Tried to do it with ng-bing-html aswell
//$scope.trailerHtml = "<iframe width=\"420\" height=\"315\" ng-src=\"url\" frameborder=\"0\" allowfullscreen></iframe>";
});
});
我已经使用开发人员模式检查了该页面,看看iFrame
是否正确加载,但它似乎不包含任何src
(或ng-src
)属性。< / p>
我认为它与javascript执行之前的视图渲染有关,但我已经尝试制作一个服务,其中url已经预先计算好,并从那里获取url,但似乎没有帮助。
所有帮助将不胜感激!
答案 0 :(得分:2)
您的范围变量($ scope.video)将在Angular的事件循环之外执行。您可以在$ scope.video(BAD)上设置监视,或者在$ scope中包装自定义范围更改。$ apply():
request.execute(function(response){
var base_URL = "https://www.youtube.com/embed/";
var url = base_URL + response.items[0].id.videoId;
url = $sce.trustAs($sce.RESOURCE_URL, url);
console.log(url);
$scope.$apply(function(){
$scope.video = url;
});
Here's a quick read更好地了解Angular 1.3的事件循环。