我正在使用 Angular Bootstrap ui typeahead 异步返回记录数组,但无法让它工作。当操作同步执行时,通过下载页面加载时的所有数据,我已经让预输入工作了。两种情况下的数据看起来相同;异步版本似乎失败了,因为 typeahead 只得到了一个 promise ,而不是返回的数据。
AngularJS Controller 如下所示:
同步
vm.doctorList = [];
vm.doctorList = [];
function getAllDoctors() {
agreementService.getAllDoctors()
.then(function (response) {
vm.doctorList = response.data;
});
}
异步
vm.getExistingDoctor = function (value) {
if (value.length > 2) {
agreementService.getExistingDoctor(value)
.then(function (response) {
return response.data;
});
}
};
HTML 看起来像这样:
同步
<input type="text" ng-model="vm.agreement.doctor.nameFull"
uib-typeahead="doctor as doctor.nameFull + ' (ClockID: ' + doctor.clockID + ')'
for doctor in vm.doctorList | filter:{nameFull:$viewValue} | limitTo:8"
class="form-control bottom-none" typeahead-show-hint="true" typeahead-min-length="3" typeahead-on-select="vm.onDoctorSelect($item, $model, $label, $event)">
异步
<input type="text" ng-model="vm.agreement.doctor.nameFull"
uib-typeahead="doctor as doctor.nameFull + ' (ClockID: ' + doctor.clockID + ')'
for doctor in vm.getExistingDoctor($viewValue) | filter:{nameFull:$viewValue} | limitTo:8"
class="form-control bottom-none" typeahead-show-hint="true" typeahead-min-length="3"
typeahead-on-select="vm.onDoctorSelect($item, $model, $label, $event)">
在这两种情况下,从 Controller 返回的数据如下所示:
[Object, Object]
0:Object
clockID:14
nameFull:"Doe, Jane"
__proto__:Object
1:Object
__proto__:Object
在同步版本中,预输入按预期运行,但在异步版本中,当用户输入三个或更多字符时,不会发生任何事情。
需要做什么才能使异步版本正常运行?
最佳答案
对于异步,您需要返回一个 Promise 对象。假设您的 agreementService
返回 $http
请求/ promise (看起来确实如此),您的搜索函数应该类似于:
vm.getExistingDoctor = function (value) {
return agreementService.getExistingDoctor(value).then(function (response) {
return response.data;
});
}
请注意,我删除了对值长度的检查,因为 uibTypeahead 指令已经阻止它在未满足最小长度的情况下异步调用数据。我还建议使用 ng-options 来定义去抖值,这样您就不会在每次击键时调用 API。 ng-options={debounce: 500}
关于asynchronous - Angularjs bootstrap UI typeahead 无法异步工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39171002/