问题
My bootstrap typeahead is as following:
<input id="inputId" type="text" ng-model="selected" typeahead="name for name in getSuggestions($viewValue) " typeahead-on-select="typeaheadOnSelect($item)" ng-trim="false">
The getSuggestions() return a promise,like following:
$scope.getSuggestions = viewValue => {
let deferred = $q.defer();
getSuggestions(viewValue).then(words => {
deferred.resolve(words); // array of strings
})
.catch(()=>{
deferred.reject([]);
});
return deferred.promise;
};
NOTE: the typeahead works fine when getSuggestions() returns an array without using any promise.
回答1:
In AngularJS the results of resolve() are propagated asynchronously, inside a $digest cycle, not immediately. This means that callbacks registered with then() will only be called (later) when a digest cycle occurs.
So,calling $digest() or if needed, $apply() is one way to cause a digest cycle to run.
So the given code needs to be updated to the following:
$scope.getSuggestions = viewValue => {
let deferred = $q.defer();
getSuggestions(viewValue).then(words => {
deferred.resolve(words);
$scope.$digest();//this triggers the digest cycle
})
.catch(()=>{
deferred.reject([]);
});
return deferred.promise;
};
来源:https://stackoverflow.com/questions/47427141/bootstrap-typeahead-not-populating-with-response-from-promise