在Bootstrap UI中使用$http

Using $http with Bootstrap UI

本文关键字:http Bootstrap UI      更新时间:2023-09-26

我正在开发一个使用AngularJS和Bootstrap的应用程序。我正在拼命地让我的自动完成示例发挥作用。当我的服务返回一个数组时,我的示例成功地工作了。然而,当我尝试使用$http服务访问REST API时,我无法再获得自动完成的结果。

我的Plunker在这里

根据这个功能在其他地方的使用方式,我需要坚持两件事:

1. The $http call must happen in the service.
2. The controller must call myService.getOptions.

有人能告诉我为什么我的代码不起作用吗。我太绝望了。

您需要让您的服务返回结果,因为在您的承诺中,它将返回整个响应,但您只需要提供结果,所以只需在服务中添加一个映射器即可。

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>

演示

或者在返回数据时使用服务中的映射器返回预期的数据格式:-

  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
  });

演示