Sreehari
Sreehari

Reputation: 1370

Selected value is not getting displayed with uib-typeahead

I use uib-typeahead as below in my angularjs app for auto suggest in text box. When I type some letter, I can see the suggestions. However, if I select any of the selection, that is not getting displayed in the text(ng-model).

I am not sure if the problem is with the bootstrap or angular version that I am using, or I was doing something wrong in my code.

<input type="text" ng-model="selectedData" uib-typeahead="proDesc as mydata.proDescription for mydata in dataList | filter:$viewValue | orderBy:orderByStartsWith($viewValue)"/>

Below is the link of my code.

http://plnkr.co/edit/s4ol9bkrcb16QV2pAikA?p=preview

Upvotes: 1

Views: 1052

Answers (2)

VincentZHANG
VincentZHANG

Reputation: 787

cnorthfield's solution should work. However, in my own project, it does not work for some unknown reasons. I ended up with another solution:

<input type="text"
ng-model="selectedData"
typeahead-input-formatter="$model.proDescription "
    uib-typeahead="mydata as mydata.proDescription for mydata in dataList | filter:$viewValue" /> 

But please note that in this case selectedData will be an object in the array after user selects one item from the list, and become a string when user only types into the input box. So, you may need to catch that with extra event listener, like a ng-blur, and in the listener, check the model with an if block like:

if (typeof selectedData === 'string') {
    for (var i in dataList) {
        if (dataList[i].proDescription === selectedData) {
            // do some things here
        }
    }
}

This approach should only be considered as a backup plan if cnorthfield's doesn't work for you.

Upvotes: 0

cnorthfield
cnorthfield

Reputation: 3501

Your issue is that when you select an option, the whole object is assigned to the $viewValue of the input, not the description property of the object.

If you want to set the $viewValue from the description:

<input type="text" ng-model="selectedData" uib-typeahead="proDesc as mydata.proDescription for mydata in dataList | filter:$viewValue | orderBy:orderByStartsWith($viewValue)"/>

To:

<input type="text" ng-model="selectedData" uib-typeahead="mydata.proDescription as mydata.proDescription for mydata in dataList | filter:$viewValue | orderBy:orderByStartsWith($viewValue)"/>

Upvotes: 2

Related Questions