这是我的 JSON 文件:
{
"countries":[
{
"country": "India",
"cities" : [{
"name": "Bangalore",
"rank": "40"
},
{ "name": "Mumbai",
"rank": "32"
},
{ "name": "Kolkata",
"rank": "54"
},
{ "name": "Chennai",
"rank": "42"
}]
},
{ "country": "China",
"cities":[{"name": "Guangzhou",
"rank": "111"
},
{ "name": "Fuzhou",
"rank": "21"
},
{ "name": "Beijing",
"rank": "90"
},
{ "name": "Baotou",
"rank": "23"
}]
}
]}
这是angularjs代码:
$scope.countryType = [
{ type: 'India', data:$scope.India, displayName:'India' },
{ type: 'China', data:$scope.China, displayName:'China'},
{ type: 'Ethiopia', data:$scope.Ethiopia, displayName:'Ethiopia'},
{ type: 'Cuba', data:$scope.Cuba, displayName:'Cuba'}
];
这个angularjs 代码对我来说没问题,但我不知道如何从这个数据<访问name 和rank/strong> 的 countryType 并且我还想根据国家对其进行过滤。
对于 HTML 页面,我使用此代码:
<select ng-model="country.city" ng-options="country as country.type for country in countryType | orderBy: 'type'">
<option value=""> - Select a Country - </option>
</select>
<ul ng-repeat = "city in countryType | filter : country.city.data.cities.country ">
<li ng-repeat="details in city.data.cities">
<span> {{details.name}} </span>
<span> {{details.rank}}</span>
</li>
</ul>
我必须在 html 中使用不同的代码来访问数据吗? 所有数据都来了,但我无法过滤它。
最佳答案
所以,基本上您的数据结构中有两层数组。这就是为什么您需要在国家/地区循环内执行循环以访问城市。
你的数据结构有点变化,这里有一个例子供你引用:
HTML:
<div class="container">
<div ng-controller="FormController as formCtrl">
<table>
<tbody ng-repeat="country in formCtrl.contryType">
<tr>
<th colspan="2">{{country.country}}</th>
</tr>
<tr ng-repeat="city in country.cities">
<td>{{city.name}}</td>
<td>{{city.rank}}</td>
</tr>
</tbody>
</table>
</div>
</div>
JavaScript:
var app = angular.module("myApp", []);
app.controller("FormController", function () {
var ctrl = this;
ctrl.contryType = [{
"country" : "India",
"cities" : [{
"name" : "Bangalore",
"rank" : "40"
}, {
"name" : "Mumbai",
"rank" : "32"
}, {
"name" : "Kolkata",
"rank" : "54"
}, {
"name" : "Chennai",
"rank" : "42"
}
]
}, {
"country" : "China",
"cities" : [{
"name" : "Guangzhou",
"rank" : "111"
}, {
"name" : "Fuzhou",
"rank" : "21"
}, {
"name" : "Beijing",
"rank" : "90"
}, {
"name" : "Baotou",
"rank" : "23"
}
]
}
];
});
angular.bootstrap(document, ['myApp']);
工作 fiddle : http://jsfiddle.net/ashishanexpert/zvcx5z38/5/
关于javascript - 从 angularjs 访问 json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30644383/