Programmatically Choosing an AngularJS Typeahead Option

I have an AngularJS Typeahead that retrieves matches asynchronously. When a barcode is scanned in a field, it returns the result of the match, but the user must still select it. I would like to automatically select the result if it matches exactly. I see that typeahead has a select (idx) function, but I'm not sure how to get a link to it from my controller.

I foresaw something like this:

$scope.SearchItems = function (term) { return $http.get('api/Items/Search', { params: { term: term } }).then(function (response) { if (response.data.length == 1 && response.data[0].Code == term) { // Somehow inform typeahead control to select response.data[0] } return response.data; }); }; 
+5
source share
1 answer

I had a similar problem and I never thought about how to access typeahead select(idx) , but I managed to get this functionality to work. Here is my hacky workaround ....

 $promise.then(function(res) { angular.forEach(res, function(item, key) { // if we have an exact match if (item.title === term) { // update model $scope.src = item; // find item in dropdown var elm = '[id*=option-' + key + ']'; var opt = angular.element(document.querySelectorAll(elm)); //call click handler outside of digest loop $timeout(function() { opt.triggerHandler('click'); }, 0); } }); // return async results return res; }); 

Basically we just update our model manually, find the item in our drop-down list, and then run the 'click' handler. Make sure you end the call to triggerHandler in $timeout() zero, otherwise you will get the error $rootScope:inprog , since the digest is already running.

0
source

Source: https://habr.com/ru/post/1208511/


All Articles