Angular-UI: Force Typeahead results
M

1

9

I have a text field that uses AngularUI's typeahead feature. It looks like this:

<input typeahead="eye for eye in autocomplete[column] | filter:$viewValue">

I'd like to force the user to select an option from the list that is generated. If they type something that is not on the list exactly as it appears, on blur (clicking outside of the text field), i'd like the value of the text field to reset to it's original value.

Is this functionality part of the typeahead directive, or will I need to extend it? I searched for about 10 minutes on google and stackoverflow, but couldn't find any relevant documentation.

Can anyone please point me in the right direction to accomplish this?

Mesopotamia answered 10/9, 2014 at 20:9 Comment(7)
There is a second argument to filter that enable exact matches, maybe it could make it work? filter:$viewValue:trueMacadam
Hmm, that broke the typeahead on my page. Is there a certain version of Angular required?Mesopotamia
There is also an attribute in Ui-Boostrap to force existing results: typeahead-editable="false" (typeahead-editable (Defaults: true) : Should it restrict model values to the ones selected from the popup only ?)Macadam
The model becomes empty if the value is wrong. I think you would need to store the last good value in a variable, and bind an event on blur and see if the current value is wrong, if yes, then set the current value to the last good value.Macadam
Doesn't appear to be emptying if the value is wrong. See this jsfiddle: jsfiddle.net/ZjPWe/60Mesopotamia
The field is not, but the model is according to their documentation. Don't forget that there is the $modelValue and the $viewValue.Macadam
Ok. I found more or less what I wanted here: #17856626 . You did answer some questions though, so if you make it an answer i'll accept it.Mesopotamia
M
15

There is an attribute in the plugin to force existing values only: typeahead-editable="false". The default value is true.

Only the $modelValue is being set to empty when there is a wrong value selected, and this is actually necessary otherwise we would not be able to write anything. The $viewValue stays with the last text entered. You might be able to bind a blur event of your own to the field to reset the $viewValue?

Here is your JsFiddle with the selected value displayed: http://jsfiddle.net/ZjPWe/61/

You could also use the attribute typeahead-on-select which required a callback when a value is selected, but I am not sure it would work with typeahead-editable="false" because no value is being selected.

Macadam answered 10/9, 2014 at 20:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.