gpt4 book ai didi

javascript - 为什么我的 ng-repeat 表现得像对象是空的?

转载 作者:行者123 更新时间:2023-12-03 10:10:29 26 4
gpt4 key购买 nike

这是我的 Controller 代码:

.controller('vidController', ["$scope", "$location", "youtubeAPI", function($scope, $location, youtubeAPI) {
if(document.getElementById('query')) { //See Note 1 Below*****
var textElement = document.getElementById('query');
textElement.onkeyup=function(e){
if(e.keyCode==13){ //if key pressed is enter button
console.log('Looking for ' + textElement.value + ' on YouTube');
youtubeAPI.search(textElement.value);
$location.path('/results'); //changes url path to results partial
$scope.$apply();
}
}
};
// Called automatically with the response of the YouTube API request.
window.onSearchResponse = function(response) {
console.log(response); //Shows entire response data
console.log(response.items[0].snippet.title); //shows video title
console.log(response.items[0].id.videoId); //shows video Id
console.log(response.items[0].snippet.thumbnails.medium.url); //shows video thumbnail
$scope.videos = response.items;
$scope.$apply();
console.log($scope.videos); //This outputs an object with 5 Objects in it. Proof that the API is picking up something.
};
}]);

*注1:我有一个输入文本类型,用户将搜索关键字放入其中,然后按 Enter 键对其运行搜索,按 Enter 键时它还会更改地址。也许这会引起问题?

这是部分内容:

<ul>
<li ng-repeat="video in videos">
hey
</li>
</ul>

由于我使用的是 youtubeAPI,因此每个搜索结果都会返回 5 个结果。 console.log($scope.video)在控制台中显示了 5 个对象,因此我知道它正在被填充。

但是,每当我进入部分页面并检查元素时,<ul>标签完全是空的。就像 ng-repeat从来没有跑过。

为什么不运行?我应该看到“嘿”5 次。

编辑:这是我的代码中最后一个 console.log 的控制台输出 enter image description here

编辑2:根据请求,这里是运行onSearchResponse的地方。

angular.module('GameFindr.search', [])
.factory('youtubeAPI', [function() {

var youtubeAPI = { };

youtubeAPI.search = function(keyword) {
// Use the JavaScript client library to create a search.list() API call.
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: keyword,
type: 'video',
});

// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
}

return youtubeAPI;
}]);

编辑3:添加$scope.apply();之后$scope.videos如果我注释掉 $location.path 就可以了改变,它保持相同的 View 。但当我改变观点时它就不起作用了。这是我的路由器:

angular.module('GameFindr', [
'ngRoute',
'GameFindr.controllers',
'GameFindr.search'
])

.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', { templateUrl: 'home.html', controller: 'vidController' }).
when('/results', { templateUrl: 'results.html', controller: 'vidController'}).
otherwise({ redirectTo: '/' });
}]);

最佳答案

您正在更改回调中的对象值,因此当该值可从回调中获得时,ng-repeat它已经以初始值运行,并且在您的情况下未定义。

尝试下面的代码

$scope.videos = response.items;
$scope.$apply();

引用:github$scope.$apply() 在最后调用,告诉 AngularJS 刚刚发生了一个异步事件。

关于javascript - 为什么我的 ng-repeat 表现得像对象是空的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30136893/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com