我一直在扯头发。我正在使用 ion-autocomplete 并希望通过工厂提取数据。
我的工厂......
myApp.factory('items', function($http){
return {
list: function(query,callback){
$http.get('http://192.168.100.100/myApp/products/' + query).success(callback)
}
};
});
为了获取我使用的数据..
items.list(function(items) {
$scope.items = items;
});
自动完成请求数据的演示,如..
$scope.getTestItems = function (query) {
return {
items: [
{id: "1", name: query + "1", view: "view: " + query + "1"},
{id: "2", name: query + "2", view: "view: " + query + "2"},
{id: "3", name: query + "3", view: "view: " + query + "3"}]
};
};
所以我认为这是一个可行的解决方案..
$scope.getTestItems = items.list(query,function(items)
{
console.log(items);
return items;
}
)
但显然不是。我试过了..
$scope.getTestItems = function(query)
{
items.list(query,function(items)
{
console.log(items);
return items;
}
)
}
它确实给了我一个结果的控制台,但它没有返回到 getTestItems
最佳答案
根据 the docs (假设我在这里有正确的库),你可以返回一个 promise
myApp.factory('items', function($http){
return {
list: function(query) {
return $http.get(... + query).then(function(res) {
return res.data; // unwrap the response data
// see the "Returns" section at https://docs.angularjs.org/api/ng/service/$http#usage
});
}
};
});
和 Controller
$scope.getTestItems = function(query) {
return items.list(query);
};
关于javascript - 返回结果给父函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31667526/