I'm using the angular-ui typeahead directive to connect to the Google Maps API and retrieve an array of addresses. Normally when I need to limit the amount of results visible I do something like:
<input typeahead="eye for eye in array | filter:$viewValue | limitTo:10">
That works perfectly and the results are limited to 10. However, when I try to do the same thing with asynchronous results, it doesn't work. It will give more results than I specified in the limitTo
.
Am I doing something incorrectly below?
HTML:
<input ng-model="asyncSelected" typeahead="address for address in getLocation($viewValue) | limitTo:1" typeahead-loading="loadingLocations">
JavaScript:
$scope.getLocation = function(val) {
return $http.get('http://maps.googleapis.com/maps/api/geocode/json', {
params: {
address: val
}
}).then(function(res){
var addresses = [];
angular.forEach(res.data.results, function(item){
addresses.push(item.formatted_address);
});
return addresses;
});
};
Currently i'm doing the following to workaround, i'm just curious why a simple limitTo
doesn't work.
$scope.getLocation = function(val) {
return $http.get('http://maps.googleapis.com/maps/api/geocode/json', {
params: {
address: val
}
}).then(function(res){
var addresses = [];
var resultNumber = res.data.results.length > 5 ? 5 : res.data.results.length;
for(var i = 0; i < resultNumber; i++){
var obj = res.data.results[i];
var addr = obj.formatted_address;
addresses.push(addr);
}
return addresses;
});
};
typeahead doesn't seem to support promises. So it's better to just bind it to a collection, and then update that collection when you get a response from google. You might want to think about debouncing tough, now a request is done for every letter typed.
Note that you also don't need the filter anymore, because the filter is already being done by google sever side.
http://plnkr.co/edit/agwEDjZvbq7ixS8El3mu?p=preview