我跟随这个plunker在我的项目中创建了一个预先输入。
http://plnkr.co/edit/ZjpJxXkl0v5LhQdxcqWn?p=preview
app.js(不使用我的API)
$scope.getAddress = function(viewValue) {
var params = {address: viewValue, sensor: false};
return $http.get('http://maps.googleapis.com/maps/api/geocode/json', {params: params})
.then(function(res) {
console.log(res);
return res.data.results;
});
};
的index.html
<!-- Using an async data provider -->
<div class="form-group">
<label><i class="fa fa-home"></i> Address <small>(async via maps.googleapis.com)</small></label>
<input
type="text"
class="form-control"
ng-model="selectedAddress"
data-animation="am-flip-x"
ng-options="address.formatted_address as address.formatted_address for address in getAddress($viewValue)"
placeholder="Enter address"
bs-typeahead>
</div>
Inn my case我从.net API获取数据。当我在控制台上记录API的结果时,我可以看到该数组正从API返回。但当我尝试将其返回到预先输入时,数据不会显示。但是,如果我尝试创建一个模拟对象数组,然后手动将数据插入到数组中,结果将显示在typeahead中。
app.js(显示数据)
$scope.getAddress = function(viewValue) {
var params = {address: viewValue, sensor: false};
return $http.get('http://maps.googleapis.com/maps/api/geocode/json', {params: params})
.then(function(res) {
console.log(res);
[{formatted_address: "Alabama"},{formatted_address: "Arkansas"},{formatted_address: res.data.results[0]}]
return res.data.results;
});
};
为什么会发生这种情况,我该如何解决?
答案 0 :(得分:0)
我无法看到您的完整解决方案,因此很难说您错过了什么,但请参阅下面的工作解决方案。
var app = angular.module('app', ['mgcrea.ngStrap']);
app.controller('firstCtrl', function($scope, $http) {
$scope.getAddress = function(viewValue) {
var params = {
address: viewValue,
sensor: false
};
return $http.get('http://maps.googleapis.com/maps/api/geocode/json', {
params: params
})
.then(function(res) {
return res.data.results;
});
};
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.14/angular.min.js"></script>
<script src="//mgcrea.github.io/angular-strap/dist/angular-strap.js" data-semver="v2.1.3"></script>
<script src="//mgcrea.github.io/angular-strap/dist/angular-strap.tpl.js" data-semver="v2.1.3"></script>
<body ng-app="app">
<div ng-controller="firstCtrl">
<div class="form-group">
<label><i class="fa fa-home"></i> Address <small>(async via maps.googleapis.com)</small>
</label>
<input type="text" class="form-control" ng-model="selectedAddress" data-animation="am-flip-x" ng-options="address.formatted_address as address.formatted_address for address in getAddress($viewValue)" placeholder="Enter address" bs-typeahead>
</div>
</div>
</body>