我正在开发一个使用 AngularJS 和 Bootstrap 的应用程序。我正在拼命尝试让我的自动完成示例正常工作。当我的服务返回一个数组时,我的示例成功运行。但是,当我尝试使用 $http 服务访问 REST API 时,我无法再获得自动完成结果。
根据此函数在其他地方的使用方式,我需要遵守两件事:
1. The $http call must happen in the service.
2. The controller must call myService.getOptions.
有人可以告诉我为什么我的代码不起作用吗?我好绝望。
最佳答案
您需要让您的服务返回结果,因为在您的 promise 中它将返回整个响应,但您只需要提供结果,因此只需在您的服务中添加一个映射器即可。
this.getOptions = function(prefix) {
return $http.get('http://search.ams.usda.gov/farmersmarkets/v1/data.svc/zipSearch?zip=60629').then(function(response){
return response.data.results; //Return results
});
};
并在您看来进行一些更改以适应数据:-
typeahead="option as option.marketName for option in getOptions($viewValue)"
<h4><span bind-html-unsafe="match.model.marketname | typeaheadHighlight:query"></span></h4>
<强> Demo
或者在您的服务中使用映射器在返回数据的同时返回预期的数据格式:-
return $http.get('http://search.ams.usda.gov/farmersmarkets/v1/data.svc/zipSearch?zip=60629').then(function(response){
return (response.data.results || []).map(function(itm){return {id:itm.id, name:itm.marketname}}); //map your data
});
<强> Demo
关于javascript - 将 $http 与 Bootstrap UI 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25925095/