我使用angular-ui typeahead指令连接到Google Maps API并检索地址数组。通常,当我需要限制可见结果的数量时,我会执行以下操作:
<input typeahead="eye for eye in array | filter:$viewValue | limitTo:10">
完美无缺,结果仅限于10.然而,当我尝试使用异步结果做同样的事情时,它并不起作用。它将提供比我在limitTo
中指定的更多结果。
我在下面做错了吗?
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;
});
};
目前我正在做以下工作,我只是好奇为什么一个简单的limitTo
无效。
$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;
});
};
答案 0 :(得分:3)
typeahead似乎不支持承诺。所以最好将它绑定到一个集合,然后在从谷歌获得响应时更新该集合。你可能想考虑去抖动,现在每个输入的字母都会有一个请求。
请注意,您也不再需要过滤器,因为过滤器已经由谷歌服务器端完成。
http://plnkr.co/edit/agwEDjZvbq7ixS8El3mu?p=preview
var app = angular.module('app',['ui.bootstrap']);
app.controller('Ctrl', ['$scope','$http', function($scope,$http){
$scope.locations = [];
$scope.$watch('asyncSelected', function(val) {
$http.get('http://maps.googleapis.com/maps/api/geocode/json', {
params: {
address: val
}
}).then(function(res){
$scope.locations.length = 0;
angular.forEach(res.data.results, function(item){
$scope.locations.push(item.formatted_address);
});
});
});
}]);
<head>
<link data-require="bootstrap-css@~3.1.1" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
<script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<script data-require="ui-bootstrap@*" data-semver="0.11.0" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.11.0.min.js"></script>
<script data-require="jquery@*" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script data-require="bootstrap@*" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="app" ng-controller="Ctrl">
<input type="text" ng-model="asyncSelected" placeholder="Address" typeahead="address for address in locations | limitTo:1" typeahead-loading="loadingLocations" class="form-control">
</body>
</html>