在Angular 1.x.x中添加预先填充的国家、州和城市列表,可以通过以下步骤实现:
[
{
"country": "中国",
"states": [
{
"state": "北京市",
"cities": ["北京市"]
},
{
"state": "上海市",
"cities": ["上海市"]
}
]
},
{
"country": "美国",
"states": [
{
"state": "纽约州",
"cities": ["纽约市", "布鲁克林市"]
},
{
"state": "加利福尼亚州",
"cities": ["洛杉矶市", "旧金山市"]
}
]
}
]
$http
服务从JSON文件中获取数据,并将其存储在服务中。app.service('LocationService', function($http) {
var countries = [];
this.getCountries = function() {
return $http.get('path/to/countries.json').then(function(response) {
countries = response.data;
return countries;
});
};
this.getStatesByCountry = function(country) {
var selectedCountry = countries.find(function(c) {
return c.country === country;
});
return selectedCountry ? selectedCountry.states : [];
};
this.getCitiesByState = function(country, state) {
var selectedCountry = countries.find(function(c) {
return c.country === country;
});
if (selectedCountry) {
var selectedState = selectedCountry.states.find(function(s) {
return s.state === state;
});
return selectedState ? selectedState.cities : [];
}
return [];
};
});
LocationService
服务获取国家、州和城市数据,并将其绑定到视图中的相应下拉列表中。app.controller('LocationController', function($scope, LocationService) {
$scope.countries = [];
$scope.states = [];
$scope.cities = [];
LocationService.getCountries().then(function(countries) {
$scope.countries = countries;
});
$scope.onCountryChange = function() {
$scope.states = LocationService.getStatesByCountry($scope.selectedCountry);
$scope.cities = [];
};
$scope.onStateChange = function() {
$scope.cities = LocationService.getCitiesByState($scope.selectedCountry, $scope.selectedState);
};
});
ng-options
指令绑定国家、州和城市数据到下拉列表中,并使用ng-change
指令监听下拉列表的变化。<select ng-model="selectedCountry" ng-options="country.country for country in countries" ng-change="onCountryChange()">
<option value="">选择国家</option>
</select>
<select ng-model="selectedState" ng-options="state.state for state in states" ng-change="onStateChange()">
<option value="">选择州</option>
</select>
<select ng-model="selectedCity" ng-options="city for city in cities">
<option value="">选择城市</option>
</select>
通过以上步骤,你可以在Angular 1.x.x中添加预先填充的国家、州和城市列表。这样用户在选择国家、州和城市时,可以从预定义的列表中进行选择,提高了用户体验和数据的准确性。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云