bootstrap typeahead not populating with response from promise

[亡魂溺海] 提交于 2021-02-19 06:24:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!