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?

Josue Espinosa
  • 5,009
  • 16
  • 47
  • 81
  • There is a second argument to filter that enable exact matches, maybe it could make it work? `filter:$viewValue:true` – jpmorin Sep 10 '14 at 20:11
  • Hmm, that broke the typeahead on my page. Is there a certain version of Angular required? – Josue Espinosa Sep 10 '14 at 20:13
  • 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 ?) – jpmorin Sep 10 '14 at 20:14
  • 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. – jpmorin Sep 10 '14 at 20:18
  • Doesn't appear to be emptying if the value is wrong. See this jsfiddle: http://jsfiddle.net/ZjPWe/60/ – Josue Espinosa Sep 10 '14 at 20:21
  • The field is not, but the model is according to their documentation. Don't forget that there is the `$modelValue` and the `$viewValue`. – jpmorin Sep 10 '14 at 20:34
  • Ok. I found more or less what I wanted here: http://stackoverflow.com/questions/17856126/angularjs-bootstrapui-typeahead-with-object-selection-functionality . You did answer some questions though, so if you make it an answer i'll accept it. – Josue Espinosa Sep 10 '14 at 20:35

1 Answers1

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.

jpmorin
  • 6,008
  • 2
  • 28
  • 39