asynchronous - Angularjs bootstrap UI typeahead 无法异步工作

标签 asynchronous angular-ui typeahead angular-http

我正在使用 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/

相关文章:

javascript - Angular 用户界面选择 : Change theme

json - 加载 Angular UI Bootstrap Datepicker 时将日期字符串解析为 Date 对象

javascript - Twitter Typeahead 结果回显到页面但不返回到搜索框 PHP

javascript - 防止 typeahead.js 下拉菜单在选择时关闭

javascript - 如何在异步nodejs中完成所有过程并打印出消息?

JavaFX 时间轴播放 slider 在异步时间点触发事件

angularjs - 如何点击 angular-ui 日期选择器弹出窗口 Today 按钮?

typeahead.js 获取选定的数据

c# - 运行异步代码 C# 时未找到 AsyncMethodBuilder.cs

asynchronous - Servicestack 异步方法 (v4)