在AnguarJs中,下拉列表别使用ng-options来实现。
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>angularjs select 三级联动</title>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
<style type="text/css">
label {
padding: 5px 10px;
border: 1px solid #fff;
}
.error {
border-color: #f00;
}
</style>
</head>
<body>
<div ng-controller='cityCtrl'>
省份:
<select ng-model="selected" ng-options="s.name for s in list" ng-change="c()">
<option value="">--请选择--</option>
</select>
<select ng-model="selected2" ng-options="sh.name for sh in selected.child" ng-change="c2()">
<option value="">--请选择--</option>
</select>
<label ng-show="selected2.child.length" ng-class="{error: error.area}">
县级/区域:
<select ng-model="selected3" ng-options="x.value for x in selected2.child" ng-change="c3()" >
<option value="">--请选择--</option>
</select>
</label>
<br /> {{selected.name}} {{selected2.name}} {{selected3.value}}
</div>
<script type="text/javascript">
var app = angular.module('app', []);
app.controller('cityCtrl', ['$scope', '$http', function($scope, $http) {
$scope.error = {};
$scope.list = [];
$http.get('list.json').success(function(data) {
$scope.list = data;
});
$scope.c = function() {
$scope.error.area = false;
$scope.selected2 = "";
$scope.selected3 = "";
};
$scope.c2 = function() {
$scope.error.area = false;
$scope.selected3 = "";
};
$scope.c3 = function() {
$scope.error.area = false;
};
}]);
angular.bootstrap(document, ['app']);</script>
</body>
</html>
新建list.json文件,来保存省,市,区的值,供给控制器调用,在界面上显示。
[
{
"id": 0,
"name": "北京",
"code": "001",
"child": [
{
"id": 0,
"name": "东城区",
"child": []
}, {
"id": 1,
"name": "西城区",
"child": []
}, {
"id": 2,
"name": "崇文区",
"child": []
}, {
"id": 3,
"name": "宣武区",
"child": []
}, {
"id": 4,
"name": "朝阳区",
"child": []
}, {
"id": 5,
"name": "丰台区",
"child": []
}
]
}, {
"id": 1,
"name": "广西",
"code": "002",
"child": [
{
"id": 0,
"name": "南宁",
"child": [
{
"value": "兴宁区"
}, {
"value": "青秀区"
}, {
"value": "江南区"
}, {
"value": "西乡塘区"
}, {
"value": "良庆区"
}, {
"value": "邕宁区"
}, {
"value": "武鸣县"
}, {
"value": "隆安县"
}
]
}, {
"id": 1,
"name": "柳州",
"child": [
{
"value": "城中区"
}, {
"value": "鱼峰区"
}, {
"value": "柳南区"
}, {
"value": "柳北区"
}
]
}, {
"id": 2,
"name": "桂林",
"child": [
{
"value": "秀峰区"
}, {
"value": "叠彩区"
}, {
"value": "象山区"
}
]
}, {
"id": 3,
"name": "百色",
"child": [
{
"value": "右江区"
}, {
"value": "平果县"
}, {
"value": "田阳县"
}, {
"value": "田东县"
}, {
"value": "德保县"
}
]
}
]
}, {
"id": 2,
"name": "广东",
"code": "003",
"child": [
{
"id": 0,
"name": "广州",
"child": [
{
"value": "天河区"
}, {
"value": "白云区"
}, {
"value": "黄埔区"
}
]
}, {
"id": 1,
"name": "深圳",
"child": [
{
"value": "宝安区"
}, {
"value": "南山区"
}, {
"value": "福田区"
}
]
}, {
"id": 2,
"name": "珠海",
"child": []
}
]
}
]