user1383163 user1383163 - 4 months ago 24
AngularJS Question

Using ui-typeahead to populate model with object but show string of that model

Hello everyone i have the following code using ui-angular typeahead

<input type="text" ng-model="itemSelected"
uib-typeahead="item.name for item in getItems()" id="itemInput" class="form-control">


the data that
getItems()
returns is of this structure:


[{itemId : 12345, name : "name of item"} ....]


Now what i would like to happen is the type ahead to give it's suggestions by showing
item.name
(which it currently does!) however what it does is sets itemSelected to the string not the object.

if i change the html such that the list comprehension reads item for item in
getItems()
I get the typeahead giving me the object (not what i want) although it does set the itemSelected variable to the object of my selected typeahead.

What i want to know is how can i have my cake and eat it?

I would like the typeahead to display item.name but i would like the object item to be put into
itemselected
.

I am hoping I am just missing something fundamental here, any pointing out my lapse in thinking would be excellent :)

Answer

You can try the following...it works fine

https://plnkr.co/edit/Zsgw5RKAEi5C2IKLcpGR?p=preview

<div>seleted state: {{state4}}</div>
        <input type="text" ng-change="onedit()"  ng-model="state4" uib-typeahead="state as state.name for state in states | filter:$viewValue | limitTo:8">
Comments