Jason
Jason

Reputation: 1817

add new item to typeahead if it's not on the list

I'm using angular bootstrap typeahead. I would like to make an enhancement where if the item is not in the list, the user has the ability to add a new item (maybe the item being typed shows up at the bottom of the list with a plus button, or something similar).

Is there an easy way to make this enhancement? If not, is there something else that can do this?

Upvotes: 5

Views: 5132

Answers (1)

Anthony Chu
Anthony Chu

Reputation: 37520

Not sure if this is what you're looking for, but you can sort of do this using the $viewValue variable that's available that holds the current value in the input box. You can append it to the typeahead results. If it's selected, add it to the results for future use...

var states = ['Alabama', 'Alaska' /* , ... */];
$scope.getStates = function(current) {
    var statesCopy = states.slice(0);
    if (current) {
        statesCopy.unshift(current);
    }
    return statesCopy;
};
$scope.onSelect = function (item) {
    states.push(item);
};

<input type="text" ng-model="selected" 
typeahead="state for state in getStates($viewValue) | filter:$viewValue | limitTo:8" class="form-control"
typeahead-on-select="onSelect($item)">

Live Demo

Note that you'll have to do a bit more work to deal with duplicates or live data sources.

Upvotes: 5

Related Questions