2014-09-19 70 views
0

我對使用AngularJS和Bootstrap的應用工作。我想拼命讓我自動完成例如工作。當我的服務返回一個數組時,我的示例成功運行。然而,當我試着打與$ HTTP服務REST API,我再也不能得到自動完成結果的工作。

My Plunker is Here

有兩件事情我需要堅持基於此功能在其它地方使用方式:

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

有人能告訴我爲什麼我的代碼將無法正常工作。我很絕望。

回答

1

你需要讓你的服務返回的結果,因爲在你的承諾,它將返回整個響應,但你只需要提供的結果,所以只是在你的服務中添加映射。

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