Limit Angular UI-Bootstrap Typeahead to specific object property

All we need is an easy explanation of the problem, so here it is.

I have the following Angular UI-Bootstrap typeahead working great:

<input class="span2" type="text" ng-model="selectedStuff" typeahead="stuff as stuff.name for stuff in stuffs | filter:$viewValue"/>

Though, it’s almost working too great. I’m able to display the stuffs.name for the purposes of the typeahead AND select the full stuff object in stuffs. The problem is that my $viewValue is matching all of the properties in stuff instead of just the stuff.name. I’ve tried adding the .name to various places in the typeahead with no luck. Is there a straightforward way to display and match only the .name but still return the entire object?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

The typeahead directive from the http://angular-ui.github.io/bootstrap/ repo was build to well fit into existing AngularJS ecosystem. This means that this directive tries to re-use as much as possible of syntax, filters and directives already used in AngularJS.

Back to your question – the filtering itself is done by the Angular’s filter filter described here: http://docs.angularjs.org/api/ng.filter:filter The mentioned filter’s syntax is flexible enough to limit searches to a selected set of properties:

typeahead="stuff as stuff.name for stuff in stuffs | filter:{name: $viewValue}"

Please notice: filter:{name: $viewValue}

Working plunk here: http://plnkr.co/edit/o1qWKq8LSmbbmVaYkOvb?p=preview

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply