AngularJS Typeahead与异步API调用问题求助
Got it, let's sort out this async problem with AngularUI Bootstrap's Typeahead. The core issue here is that when you switch from a synchronous array return to an async API call, the Typeahead directive expects a Promise (not a plain array) to handle the delayed data response properly. Here's how to adjust your code step by step:
1. Update the Service Method to Return a Promise
Modify your getFieldDS function to use AngularJS's $http service to call your API, and return the resulting Promise. Don't forget to pass the $viewValue parameter if you need to filter results on the backend:
function getFieldDS($viewValue) { // Replace with your actual API endpoint, pass $viewValue as a query param if needed return $http.get('/api/your-field-data', { params: { searchTerm: $viewValue } }) .then(function(response) { // Assume the API returns an array of { Description: '...' } objects return response.data; }) .catch(function(error) { // Handle errors gracefully to avoid breaking the Typeahead console.error('Failed to fetch field data:', error); return []; }); } // Important: Make sure to inject $http into your service!
2. Tweak Controller & HTML (Optional but Useful)
Your controller code doesn't need major changes—just confirm the service is properly injected and assigned:
var vm = this; // Ensure myService is injected into your controller vm.fieldDS = myService.getFieldDS;
To improve user experience, you can add a loading indicator using the typeahead-loading attribute in your HTML:
<input id="myField" name="myField" class="form-control" type="text" placeholder="myField" ng-model="myController.myObj.FieldValue" typeahead-editable="false" uib-typeahead="item as item.Description for item in myController.fieldDS($viewValue)" typeahead-loading="myController.loadingFieldData" required> <!-- Optional loading state indicator --> <small ng-show="myController.loadingFieldData" class="text-muted">Loading options...</small>
Why This Fixes the Issue
AngularUI Bootstrap's Typeahead is built to automatically handle Promises. When your data source function returns a Promise, the directive will wait for it to resolve (once the API response comes in) before rendering dropdown options. If you don't return a Promise, the directive tries to process the raw $http request object immediately—which causes the breakage you're seeing.
内容的提问来源于stack exchange,提问作者Saledan

