2016-12-29 10 views
1

を返し、これが私の現在のコードです:jQueryのオートコンプリートと角度のhttpはだから私は<a href="https://github.com/devbridge/jQuery-Autocomplete" rel="nofollow noreferrer">jQuery-Autocomplete</a>を使用して、私のデータベースのためのAjaxのオートコンプリートを使用していますエラー

HTML:

<input ng-keyup="searchCustomer()" id="customerAutocomplete" type="text"> 

角度

$scope.searchCustomer = function() { 
     $http.get('/api/customers') //this is a json return 
      .then(function (response) { 
       console.log(response.data); //FIRST OUTPUT 
       $('#customerAutocomplete').autocomplete({ 
        lookup: response.data, 
        onSelect: function (suggestion) { 
         console.log(response); 
        } 
       }); 
      }, function (error) { 
       console.log(error) 
      }) 
    } 

私が何かを入力すると私のコンソールの出力は次のようになります:

enter image description here

あなたが見ることができるように、それはにconsole.logを返しますが、エラーがありますし、何のオートコンプリート上映はありません。

jQuery-Autocompleteの使用部分には、私が試した部分があり、機能しました。

var countries = [ 
    { value: 'Andorra', data: 'AD' }, 
    { value: 'Zimbabwe', data: 'ZZ' } 
]; 

$('#autocomplete').autocomplete({ 
    lookup: countries, 
    onSelect: function (suggestion) { 
     alert('You selected: ' + suggestion.value + ', ' + suggestion.data); 
    } 
}); 

しかし、http呼び出しから自分のデータのcountries変数を変更すると、エラーが発生します。

私は図書館

enter image description here

のライン85をチェックし、それがreturn suggestion.value.toLowerCase().indexOf(queryLowerCase) !== -1;です。

だから私の最初の推測ではJSON.stringifyresponse.dataですし、私はこれを取得:

enter image description here

だから、それはあまりにも動作しませんでした。すべてのヘルプは非常にサーバーからjQuery-Autocompletedocumentation応答を1として

答えて

0

はJSON以下のように次のJavaScriptオブジェクトをフォーマットする必要があります。..いただければ幸いです。

{ 
    // Query is not required as of version 1.2.5 
    "query": "Unit", 
    "suggestions": [ 
    { "value": "United Arab Emirates", "data": "AE" }, 
    { "value": "United Kingdom",  "data": "UK" }, 
    { "value": "United States",  "data": "US" } 
    ] 
} 

それともにごAPIレスポンスを解析するtransformResult機能を使用する必要があります標準的な応答。

は、私が思うに、あなたのケースでは、以下のようにする必要があります:

// HTML

<input id="customerAutocomplete" type="text"> 

//スクリプト

$('#customerAutocomplete').autocomplete({ 
    serviceUrl : '/api/customers', // your full api URL 
    onSelect: function (suggestion) { 
    console.log(response); 
    }, 
    transformResult: function(response) { 
    if(response.data.length > 0) { 
     return { 
     suggestions: $.map(response.data, function(dataItem) { 
      return { value: dataItem.customer_name, data: dataItem.customer_id }; 
     }) 
     }; 
    } else { 
     return {}; 
    } 
    } 
}); 
+0

今私は、未定義のプロパティ '長さ' を読み取ることができません取得 – FewFlyBy

+0

この部分の提案:$ .map(response.data、function(dataItem) – FewFlyBy

+0

私は 'searchCustomer'関数が必要ではないと思うので私の答えを更新しました。 – ranakrunal9

関連する問題

 関連する問題