Angularjs bootstrap UI typeahead不能异步工作

时间:2016-08-26 16:40:35

标签: asynchronous angular-ui typeahead angular-http

我正在异步使用angular bootstrap ui typeahead来返回记录数组,但无法使其工作。通过下载页面加载时的所有数据,我可以在同步执行操作时使用typeahead。两种情况下的数据看起来都是一样的;看起来异步版本失败了,因为typeahead只获得了一个promise,而不是返回的数据。

angularjs控制器如下所示:

同步

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)">

在这两种情况下,从控制器返回的数据如下所示:

[Object, Object]
0:Object
clockID:14
nameFull:"Doe, Jane"
__proto__:Object
1:Object
__proto__:Object

在同步版本中,typeahead按预期运行,但在异步版本中没有任何反应,因为用户输入了三个或更多字符。

需要做些什么才能使异步版本正常运行?

1 个答案:

答案 0 :(得分:2)

对于异步,您需要返回一个promise对象。假设您的agreementService返回$http请求/承诺(它似乎),您的搜索功能应如下所示:

vm.getExistingDoctor = function (value) {
      return agreementService.getExistingDoctor(value).then(function (response) {
          return response.data;
      });
}

请注意,我删除了对值的长度的检查,因为如果不满足最小长度,uibTypeahead指令已经阻止它以异步方式调用数据。我还建议使用ng-options定义去抖动值,这样您就不会在每次按键时调用API。 ng-options={debounce: 500}