【问题标题】:Angularjs bootstrap UI typeahead not working asynchronouslyAngularjs bootstrap UI typeahead不能异步工作
【发布时间】:2017-06-02 22:40:34
【问题描述】:

我正在使用 angular bootstrap ui typeahead 异步返回记录数组,但无法使其工作。当操作同步执行时,通过下载页面加载时的所有数据,我已经让 typeahead 工作。两种情况下的数据看起来都一样;并且似乎异步版本失败了,因为预输入只得到一个承诺,而不是返回的数据。

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

在同步版本中,预输入按预期工作,但在异步版本中,当用户输入三个或更多字符时,什么都不会发生。

需要做什么才能使异步版本正常工作?

【问题讨论】:

    标签: asynchronous angular-ui typeahead angular-http


    【解决方案1】:

    对于异步,您需要返回一个 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}

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多