Search code examples
angularjscoffeescriptangular-ui-bootstraptypeaheaddebouncing

AngularJS - Typeahead Asynchronous data


I'm using Typeahead bootstrap with anguarJS to fetch data from rails api, the problem is that the request get data every time I type a letter in the input, I want te perform and decrease a little bit the number of request and debounce it to make a match between what is typed and the data retrieved.

here is the controller :

 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)

and here is the haml part :

 .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()' }}

In the ui-bootstrap doc example version 0.12.1, the async loading is triggered through typeahead="address for address in getLocation($viewVlue) but they don't use a watcher on the model. Their getLocations method is my getSpecificationTemplatesNames method.

can some one help to perform this and transform with me the code and use the typeahead-wait-ms option correctly using coffeescript!


Solution

  • this is the solution i found, use promise :

    haml part :

     %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 controller :

    $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