3

I'm trying to figure out how to have a UI.Bootstrap Typeahead (http://angular-ui.github.io/bootstrap/) only set the model value if a selection is made from the dropdown, and clear the field if no selection was made.

If there's a different control out there that does this that would work too.

The Typeahead is selecting an object and if the user just types a few characters and then leaves the field, the model value is set to the string value of the field. I can obviously test for this case but modifying the scope model value doesn't refresh the form validity. So if I have a required field I also have to set the field's validity to false.

This all seems like a lot of work that someone must have already figured out. Any suggestions?

Edit

Another thought I had was, is it best practice to separate the Typeahead from the scope values that are being submitted back to the server?

2 Answers 2

8

I had a similar problem. The way I went around it is by using the blur event to validate.

<input type="text" ng-model="yourModel" ng-blur="validateSelection()
  typeahead="item for item in list | filter:$viewValue"">
Sign up to request clarification or add additional context in comments.

3 Comments

This is how I ended up solving it too. Though I haven't updated this yet because I'm working on a more full fledged pull request for the control itself. Making this functionality a configurable option
@JoshRusso how do you handle selection with mouse? the blur event occurs before the select event and before the model value changed?
@hansmaad I'm glad you asked, that's an excellent point. You need to use some SetTimeout() trickery. The body of the validateSelection() function needs to be wrapped in a SetTimeout() call and capturing the timeout Id. In the click event of the menu, you cancel the timeout call with clearTimeout(). Because it's the click event that's triggering the blur you don't even really need to set the delay value. The way the timeout works it essentially just moves the validation body to be the last thing called in that series of calls.
0

Accepted part is good solution. It could be also good to add

 typeahead-select-on-blur="true" 

in input box. It will make fill up ng-model value (if it not typed entire term) to item in typeahead dropdown which you clicked on select. You then make validation of ng-model in validateSelection() and it's important to validate entire term. About "Another thought" in Edit part. Maybe it's not very user friendly when your typed in disappear when you click away. Better is they stay in and user can edit them. When you do validateSelection() you could mark the input value as invalid for the form validation.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.