Angular bootstrap typeahead with asynchronous loading - one character behind

In the directive, I implemented the following type code.

Here is the HTML:

<div> <input type="text" ng-model="company" uib-typeahead="company as company.name for company in companyByName($viewValue)" typeahead-loading="loadingCompanies" typeahead-no-results="noCompanyResults" class="form-control"> <i ng-show="loadingCompanies" class="glyphicon glyphicon-refresh"></i> <div ng-show="noCompanyResults"> <i class="glyphicon glyphicon-remove"></i> No Results Found </div> </div> 

Here is the javascript:

  scope.companyByName = function() { var companyName = scope.company.name ? scope.company.name : scope.company; var searchTerms = {name: companyName, startRow: 0, endRow: 20}; return $http.post("backend/get/companies.php", searchTerms).then((result) => { $log.info("Companies", result.data.results); return result.data.results; }); }; 

The PHP code backend/get/companies.php takes a search string and returns an array of objects with id and name attributes with the names that contain this search string.

Here is the behavior that I am experiencing:

When I enter one character "f" in the typeahead field, the companyName value passed to the script backend is "" (empty string). backend/get/companies.php returns all results.

When I enter the second character “fo” in the typeahead field, the companyName value passed to the script backend is “f”. backend/get/companies.php returns results matching "f".

Entering the third character "foo" returns the results corresponding to "fo", etc.

I modeled my code after official examples . What's happening? I feel that the companyByName() function is companyByName() called by an event that fires before a character is input. Any thoughts?

+6
source share
2 answers

The problem is that the ng model is lagging behind view values. When companyByName is called, the ng model is not updated to the last value from the input field. To get the last value from input, you must use an argument that is passed to the companyByName function:

 scope.companyByName = function(viewValue) { var searchTerms = {name: viewValue, startRow: 0, endRow: 20}; return $http.post("backend/get/companies.php", searchTerms).then((result) => { $log.info("Companies", result.data.results); return result.data.results; }); }; 
+4
source

Typeahead should be faster than the digest of the page, and therefore using the region instead of its value is simply not quite there.

Here is a plunker showing both versions. Essentially you need the first version as shown below

  scope.companyByName = function(val) { var companyName = val; var searchTerms = {name: companyName, startRow: 0, endRow: 20}; return $http.post("backend/get/companies.php", searchTerms).then((result) => { $log.info("Companies", result.data.results); return result.data.results; }); }; 
0
source

All Articles