AngularJS实现三级级联下拉选择框
时间: 2023-11-16 18:07:26 浏览: 51
在AngularJS中实现三级级联下拉选择框,可以使用ng-options指令和ng-change指令。
首先,在HTML中定义三个下拉选择框:
```
<select ng-model="selectedProvince" ng-options="province.name for province in provinces" ng-change="provinceChange()"></select>
<select ng-model="selectedCity" ng-options="city.name for city in cities" ng-change="cityChange()"></select>
<select ng-model="selectedDistrict" ng-options="district.name for district in districts"></select>
```
然后,在控制器中定义省市区的数据,并初始化第一个下拉选择框的选项:
```
$scope.provinces = [
{name: '北京市', cities: [
{name: '北京市', districts: [{name: '东城区'}, {name: '西城区'}, {name: '朝阳区'}, {name: '丰台区'}, {name: '石景山区'}, {name: '海淀区'}, {name: '门头沟区'}, {name: '房山区'}, {name: '通州区'}, {name: '顺义区'}, {name: '昌平区'}, {name: '大兴区'}, {name: '怀柔区'}, {name: '平谷区'}, {name: '密云区'}, {name: '延庆区'}]}
]},
{name: '上海市', cities: [
{name: '上海市', districts: [{name: '黄浦区'}, {name: '徐汇区'}, {name: '长宁区'}, {name: '静安区'}, {name: '普陀区'}, {name: '虹口区'}, {name: '杨浦区'}, {name: '闵行区'}, {name: '宝山区'}, {name: '嘉定区'}, {name: '浦东新区'}, {name: '金山区'}, {name: '松江区'}, {name: '青浦区'}, {name: '奉贤区'}, {name: '崇明区'}]}
]}
];
$scope.cities = $scope.provinces[0].cities;
$scope.districts = $scope.cities[0].districts;
$scope.provinceChange = function() {
$scope.cities = $scope.selectedProvince.cities;
$scope.cityChange();
};
$scope.cityChange = function() {
$scope.districts = $scope.selectedCity.districts;
};
```
在控制器中,通过ng-options指令绑定数据和选项,通过ng-change指令实现级联下拉选择框的更新。首先在省的下拉选择框中选中一个省,然后触发provinceChange函数,在该函数中更新市的下拉选择框的选项,并触发cityChange函数。cityChange函数中更新区的下拉选择框的选项。
最后,为每个下拉选择框绑定选中的值,即ng-model指令,例如:
```
<select ng-model="selectedProvince" ng-options="province.name for province in provinces" ng-change="provinceChange()"></select>
```
其中,$scope.selectedProvince、$scope.selectedCity、$scope.selectedDistrict分别表示选中的省、市、区。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)