2014-02-06 23 views
0

我需要實現使用angularjs從$ http請求中提取建議的typeahead功能。我正在使用Bootstrap 3.1。我一直無法得到任何建議的實施工作。大多數似乎使用Bootstrap 2.有許多第三方解決方案,其中沒有任何一個能夠使用,其中包括ui-bootstrap,typeahead.js(來自twitter)以及其他建議。目前最簡單的方法是什麼?我發現只有6個月大的東西已經過時了。當前在angularjs中實現typeahead的最佳方式

我想在這裏列出的說明: http://angular-ui.github.io/bootstrap/#/getting_started

我的視圖代碼:

<label for="originLocation" class="control-label">Origin Location</label> 
<input id="originLocation" class="form-control" 
        ng-model="OriginLocation" 
        typeahead="suggestion for suggestion in getOriginSuggestions(OriginType, $viewValue)" 
        placeholder="Enter Location"> 

我的控制器:

$scope.getOriginSuggestions = function (locationType, phrase) { 
     locationRepository.searchByType(locationType, phrase) 
      .then(function (response) { 
       var locations = []; 
       angular.forEach(response.data, function (item) { 
        locations.push(item.LongDescription); 
       }) 
       return locations; 
     }); 

我的控制器被打,我也得到地點填充,但我從來沒有看到打字行爲。這是因爲typeahead屬性在bootstrap 3.1中不起作用嗎?

+0

@ user1066946的答案觸目驚心。 angular-bootstrap-ui中的'typeahead'指令期望從異步調用返回一個承諾。 – dmahapatro

回答

3

雖然我不知道你的locationRepository是什麼樣子,但它看起來會返回一個承諾,因爲你是then -ing它。在這then您返回位置數組。

但你忘了在

$scope.getOriginSuggestions = function (locationType, phrase) { 
     locationRepository.searchByType(locationType, phrase) 
     // (...) 

返回保證你會需要返回它。 (正如他們在example中所做的那樣)

$scope.getOriginSuggestions = function (locationType, phrase) { 
     return locationRepository.searchByType(locationType, phrase) 
     // (...) 
+0

你是對的..我不明白爲什麼我必須在Then函數中返回promise和return對象.. –

+0

@RyanLangton因爲typeahead-thing(或者AngularJS?其中之一)會將另一個'then「根據您回覆的承諾,用它來構建內容。所以你需要回報這個承諾。並且由庫添加的'then'需要一個參數(位置列表);你用你自己的'then'返回 – Philipp

相關問題