我正在尝试使用角度js从下面的JSON数据中获取long_name但无法获取。 代码:
{
"results" : [
{
"address_components" : [
{
"long_name" : "700109",
"short_name" : "700109",
"types" : [ "postal_code" ]
},
{
"long_name" : "Kolkata",
"short_name" : "Kolkata",
"types" : [ "locality", "political" ]
},
{
"long_name" : "West Bengal",
"short_name" : "WB",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "India",
"short_name" : "IN",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Kolkata, West Bengal 700109, India",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 22.6902065,
"lng" : 88.38850289999999
},
"southwest" : {
"lat" : 22.6715168,
"lng" : 88.35748319999999
}
},
"location" : {
"lat" : 22.6808046,
"lng" : 88.37577829999999
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 22.6902065,
"lng" : 88.38850289999999
},
"southwest" : {
"lat" : 22.6715168,
"lng" : 88.35748319999999
}
}
},
"place_id" : "ChIJ1-N4xFyc-DkRzfGq4MWZa1g",
"types" : [ "postal_code" ]
}
],
"status" : "OK"
}
我使用以下代码来解决此问题,但它没有显示任何内容
CODE:
<div ng-app="myApp" ng-controller="myController">
<ul>
<li ng-repeat="record in records">
{{record.long_name}}
</li>
</ul>
</div>
<script>
var app=angular.module("myApp",[]);
app.controller("myController",function($scope,$http){
$http.get("https://maps.googleapis.com/maps/api/geocode/json?address=700109&key=AIzaSyDNK47S-6brePCvm1Hr6L7RFWAZvsngj1E")
// $http.get("https://www.styfash.com/post/data.json")
.then(function(result){
$scope.records=result.data.results.address_components;
});
});
</script>
每当我尝试使用$scope.records=result.data.results
并打印{{record.address_components}}
时,它都能正常工作,但每当我尝试使用上述代码时,它都不会在屏幕上显示任何内容。
我是棱角分明的新手。
答案 0 :(得分:1)
尝试
$scope.records=result.data.results[0].address_components;
答案 1 :(得分:0)
您应该了解的是,result.data.results是一个数组。因此,您应该遍历它以获取子记录。检查下面的代码示例。
var app = angular.module('myApp', []);
app.controller('myController', function ($scope, $http) {
$http.get("https://maps.googleapis.com/maps/api/geocode/json?address=700109&key=AIzaSyDNK47S-6brePCvm1Hr6L7RFWAZvsngj1E")
.then(function(result){
$scope.records=result.data.results;
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
<ul>
<div ng-repeat="record in records">
<li ng-repeat="address in record.address_components">
{{address.long_name}}
</li>
</div>
</ul>
</div>
&#13;
如果您只需要第一条记录,请在代码中更改此行
$scope.records=result.data.results.address_components;
到这个
$scope.records=result.data.results[0].address_components;