如何用AngularJS获取并打印JSON数据中的long_name?
在AngularJS中提取JSON数据里的long_name字段
我来帮你搞定AngularJS提取JSON里long_name字段的问题~先看看你的数据结构,它是嵌套的数组+对象组合,只要理清层级就能轻松拿到想要的字段啦,下面给你几种常用的实现方式:
第一步:确保数据正确绑定到$scope
首先得把你的JSON数据赋值给AngularJS的作用域变量,比如在控制器里:
// 假设这是你的控制器 app.controller('LocationController', function($scope) { // 把你的JSON数据绑定到$scope $scope.locationInfo = { "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" ] } ] } ] }; });
方式1:遍历所有address_components显示long_name
如果想把所有的long_name都列出来,可以用ng-repeat指令在视图里遍历:
<div ng-controller="LocationController"> <h4>所有地址组件的long_name:</h4> <!-- 先判断results数组是否有数据,避免报错 --> <ul ng-if="locationInfo.results.length > 0"> <li ng-repeat="item in locationInfo.results[0].address_components"> {{ item.long_name }} </li> </ul> </div>
方式2:获取特定类型的long_name(比如城市、国家)
如果只需要某个特定类型的long_name(比如城市locality、国家country),可以在控制器里先处理好数据,再绑定到视图:
控制器里的处理代码
app.controller('LocationController', function($scope) { $scope.locationInfo = { /* 你的JSON数据 */ }; // 获取城市名称(types包含locality的组件) $scope.cityName = ''; // 获取国家名称(types包含country的组件) $scope.countryName = ''; if ($scope.locationInfo.results && $scope.locationInfo.results.length > 0) { const components = $scope.locationInfo.results[0].address_components; // 用find方法找到对应类型的组件 const cityComponent = components.find(comp => comp.types.includes('locality')); const countryComponent = components.find(comp => comp.types.includes('country')); if (cityComponent) $scope.cityName = cityComponent.long_name; if (countryComponent) $scope.countryName = countryComponent.long_name; } });
视图里的显示代码
<div ng-controller="LocationController"> <p>城市:{{ cityName }}</p> <p>国家:{{ countryName }}</p> </div>
方式3:直接通过层级访问特定位置的long_name
如果你确定某个long_name在数组里的固定位置(比如第一个是邮编,最后一个是国家),也可以直接通过索引访问:
<div ng-controller="LocationController" ng-if="locationInfo.results.length > 0"> <p>邮编:{{ locationInfo.results[0].address_components[0].long_name }}</p> <p>省份:{{ locationInfo.results[0].address_components[2].long_name }}</p> </div>
注意事项
- 一定要加判断:比如
ng-if="locationInfo.results && locationInfo.results.length > 0",避免数据还没加载完成或者数组为空时出现undefined报错; - 如果你的JSON数据是通过异步请求(比如
$http.get)获取的,记得在请求的回调函数里再处理数据,或者直接依赖AngularJS的双向绑定自动更新视图。
内容的提问来源于stack exchange,提问作者Shushovan
相关产品推荐
相关产品推荐

