在 Angularjs 中使用来自 Ebay api 的回调中的数据
using data from a callback from Ebay api in Angularjs
我正在尝试在 angular.js 应用程序中使用 ebay api。
api 自身的工作方式是将数据传递给回调函数,并在该函数内创建一个模板以供显示。
我遇到的问题是将从回调返回的数据添加到 $scope。我无法 post 一个工作示例,因为我不想公开我的 api 密钥,我希望 fiddle 中的代码 post 足以确定问题。
eBayApp.controller('FindItemCtrl', function ($scope) {
globalFunc = function(root){
$scope.items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
console.log($scope.items); //this shows the data
}
console.log($scope.items); //this is undefined
})
$scope.items
的第二个实例未定义的原因是回调函数发生之前 运行。
可能 $scope.items
也没有在视图中更新,因为 Angular 不知道它需要触发范围摘要。
当您使用 Angular 提供的异步 APIs($http
、$timeout
等)时,它们的编写方式都让 Angular 知道什么时候需要更新它的视图。
在这种情况下,您有两种选择:
- 使用内置的
$http.jsonp
方法。
- 手动触发摘要。
选项 1 是更明智的方法,但如果请求是从其他图书馆发出的,则并不总是可行的。
这是一个使用 $http.jsonp
的 update to the fiddle。它应该可以工作(但目前它会导致有关您的 API 密钥的错误消息)。
这里的关键变化是请求是从 Angular 内部使用 Angular API 发出的,而不是来自 Angular 一无所知的脚本标签.
$http.jsonp(URL)
.success($scope.success)
.error($scope.error);
选项 2 要求您将以下行添加到您的 JSONP 回调函数中:
globalFunc = function(root){
$scope.items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
console.log($scope.items); //this shows the data
$scope.$apply(); // <--
}
此方法告诉 Angular 它需要更新其视图,因为数据可能已更改。如果您有兴趣,可以了解此机制Sitepoint article。
我正在尝试在 angular.js 应用程序中使用 ebay api。
api 自身的工作方式是将数据传递给回调函数,并在该函数内创建一个模板以供显示。 我遇到的问题是将从回调返回的数据添加到 $scope。我无法 post 一个工作示例,因为我不想公开我的 api 密钥,我希望 fiddle 中的代码 post 足以确定问题。
eBayApp.controller('FindItemCtrl', function ($scope) {
globalFunc = function(root){
$scope.items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
console.log($scope.items); //this shows the data
}
console.log($scope.items); //this is undefined
})
$scope.items
的第二个实例未定义的原因是回调函数发生之前 运行。
可能 $scope.items
也没有在视图中更新,因为 Angular 不知道它需要触发范围摘要。
当您使用 Angular 提供的异步 APIs($http
、$timeout
等)时,它们的编写方式都让 Angular 知道什么时候需要更新它的视图。
在这种情况下,您有两种选择:
- 使用内置的
$http.jsonp
方法。 - 手动触发摘要。
选项 1 是更明智的方法,但如果请求是从其他图书馆发出的,则并不总是可行的。
这是一个使用 $http.jsonp
的 update to the fiddle。它应该可以工作(但目前它会导致有关您的 API 密钥的错误消息)。
这里的关键变化是请求是从 Angular 内部使用 Angular API 发出的,而不是来自 Angular 一无所知的脚本标签.
$http.jsonp(URL)
.success($scope.success)
.error($scope.error);
选项 2 要求您将以下行添加到您的 JSONP 回调函数中:
globalFunc = function(root){
$scope.items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
console.log($scope.items); //this shows the data
$scope.$apply(); // <--
}
此方法告诉 Angular 它需要更新其视图,因为数据可能已更改。如果您有兴趣,可以了解此机制Sitepoint article。