【发布时间】:2016-04-28 01:56:11
【问题描述】:
我正在尝试使用 ajax 调用 Web 服务,然后将结果传递给角度控制器。我无法从回调函数中获取值以传递给范围变量。我认为这只是我对回调函数如何工作的理解不好。
代码如下:
function ajaxKimono(callback) {
$.ajax({
url:"https://www.kimonolabs.com/api/cveeggn4?apikey=NWYzkeJpFDtb4aOYd6yD96L5PdLuZHjo",
crossDomain: true,
dataType: "jsonp",
success: callback,
error: function (xhr, status) {
//handle errors
console.log(xhr);
console.log(status);
}
});
};
angular.module('app').controller('gifCtrl', function(){
var self = this;
var gifs = [];
ajaxKimono(function(result){
var collection = result.results.collection1;
$.each(collection, function(i, item){
gifs.push({ gif: item.property5.href});
});
//this outputs the correct data
//so i know the ajax call is working correctly
console.log(gifs);
self.gifCollection = gifs;
});
//something about the scope is messing me up
//this outputs nothing...
console.log(self.gifCollection);
});
【问题讨论】:
-
您的回调函数完美运行。你不明白,ajax 请求是异步的。在执行和处理 ajax 请求之前,首先执行不输出任何内容的 console.log。然后,执行 ajax 请求并调用您的回调。只有现在 console.log in 回调才会被执行。这是正常情况。因此,当您执行一些 ajax 请求时,您将在控制器中进行初始化。
-
在 AngularJS 中,您应该使用
$http服务进行 ajax 调用 docs.angularjs.org/api/ng/service/$http
标签: javascript jquery angularjs ajax