Search code examples
angularjsangular-ui-bootstrapangular-ui-typeahead

Match multiple object property values on AngularJS typeahead


I am trying to get an Angular Bootstrap UI typeahead to match against multiple properties. If i have an array of objects like this:

{
    "city":"New York",
    "region":"NY",
    "country":"USA"
},
{
    "city":"London",
    "region":"England",
    "country":"UK"
}

Can typeahead match any of the 3 properties (city, region, country ) and if it does, return all as a string in the results dropdown.

If a user types "NY" it should return and display

New York, NY, USA

And if a user instead types "Lon" it should return and display

London, England, UK

I'm wondering if it is possible to do what this and what might be the best approach?

Note: The typeahead is set to match against leading characters.


Solution

  • 1. define model

    $scope.model.addresses = [
        {"city":"New York","region":"NY","country":"USA"},
        {"city":"London","region":"England", "country":"UK"}
    ];
    

    2. define custom filter function

    $scope.findAddress = function(keyword) {
       return $filter('filter')($scope.model.addresses , {'$': keyword});
    }
    

    '$' - means find in all properties

    3. and try to use in this way

    <input typeahead="address for address in findAddress($viewValue)"/>