AngularJS - Typeahead 异步数据

AngularJS - Typeahead Asynchronous data

我正在使用 Typeahead bootstrap 和 anguarJS 从 rails api 获取数据,问题是每次我在输入中键入一个字母时请求都会获取数据,我想要执行并稍微减少请求的数量并对其进行去抖动以在键入的内容和检索到的数据之间进行匹配。

这是控制器:

 getSpecificationTemplatesNames = (value) ->
    dataStore.post DATASTORE_CACHE_KEY, "/specification_templates/specification_templates_names",{post: {search: value}},(data) ->
      $scope.names = data.templates.names


  # --- WATCHER ---

  $scope.$watch 'specificationTemplate.name', (value)  ->
    $scope.specificationDisabledForm = !value
    getSpecificationTemplatesNames(value)

这是 haml 部分:

 .col-md-8
          %input.specification-template-name{ type: 'text', name: 'name', typeahead: 'name for name in names | filter:$viewValue | limitTo:15', typeahead_wait_ms:'2000',
                        ng: { model: 'specificationTemplate.name', disabled: 'contractPeriod.isArchived()' }}

在ui-bootstrap文档示例版本0.12.1中,触发了异步加载通过 typeahead="address for address in getLocation($viewVlue) 但他们不在模型上使用观察者。他们的 getLocations 方法是我的 getSpecificationTemplatesNames 方法。

有人可以帮助执行此操作并与我一起转换代码并使用 coffeescript 正确使用 typeahead-wait-ms 选项!

您的问题是您没有正确定义 typeahead-wait-ms。属性名称中有下划线,而不是破折号。

此外,您可以使用 ng-model-options="{'debounce': ...}" 为模型的更新添加去抖动。

这是我找到的解决方案,使用 promise :

haml 部分:

 %input.specification-template-name{ type: 'text', name: 'name', typeahead: 'name for name in getSpecificationTemplatesNames($viewValue) | limitTo:15', typeahead_wait_ms:'1000',
                        ng: { model: 'specificationTemplate.name', disabled: 'contractPeriod.isArchived()' }}

angularjs 控制器:

$scope.getSpecificationTemplatesNames = (value) ->
    $q( (resolve, reject) ->
     dataStore.post DATASTORE_CACHE_KEY, "/specification_templates/specification_templates_names",{post: {search: value}},(data) ->
        resolve( data.templates.names || [] )
    )

  # --- WATCHER ---

  $scope.$watch 'specificationTemplate.name', (value)  ->
    $scope.specificationDisabledForm = !value