Search code examples
angularjsangular-ui-typeahead

Programmatically Select AngularJS Typeahead Option


I have a AngularJS Typeahead that retrieves matches asynchronously. When a barcode is scanned into the field, it returns the matching result, but the user still has to select it. I would like to automatically select the result if it's an exact match. I see that the typeahead has a select(idx) function, but am not sure how to get a reference to it from my controller.

I was envisioning 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;
    });
};

Solution

  • I had a similar issue and never figured how to access the typeahead's select(idx), but I managed to get this functionality working. Here's 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, locate the element in our dropdown and then fire off the 'click' handler. Make sure you wrap the triggerHandler call in a $timeout() set to zero, otherwise you will get a $rootScope:inprog error since digest is already in progress.