Angularjs ng-option 雙層應用,很多表單案子都有用到郵遞區號的雙層下拉選單,
目的是選擇縣市後,要對應下該縣市下的地區與郵遞區號,如圖所示。
首先,先建立好Html元素
<div>
<select>
<option value="">--請選擇--</option>
</select>
<select >
<option value="">--請選擇--</option>
</select>
</div>
放入Angularjs tag
<body ng-app="">
<div ng-controller="zip">
<select ng-model="SelCity" ng-options="City.name for City in Citys" ng-change="update(SelCity)">
<option value="">--請選擇--</option>
</select>
<select ng-model="SelArea" ng-options="SelCity for SelCity in level2" >
<option value="">--請選擇--</option>
</select>
</div>
</body>
建立controller 與 model
function zip ($scope) //controller 名稱
{
$scope.Citys= //model 內容
[
{
name:"台北市",
areas:["中正區100", "大同區103", "中山區104", "松山區105", "大安區106", "萬華區108", "信義區110", "士林區111", "北投區112", "內湖區114", "南港區115", "文山區116"]
},
{
name:"新北市",
areas: ["萬里鄉207", "金山鄉208", "板橋市220", "汐止市221", "深坑鄉222", "石碇鄉223", "瑞芳鎮224", "平溪鄉226", "雙溪鄉227", "貢寮鄉228", "新店市231", "坪林鄉232", "烏來鄉233", "永和市234", "中和市235", "土城市236", "三峽鎮237", "樹林市238", "鶯歌鎮239", "三重市241", "新莊市242", "泰山鄉243", "林口鄉244", "蘆洲市247", "五股鄉248", "八里鄉249", "淡水鎮251", "三芝鄉252", "石門鄉253"]
},
{
name:"基隆市",
areas:["仁愛區200", "信義區201", "中正區202", "中山區203", "安樂區204", "暖暖區205", "七堵區206"]
}
];
當選擇縣市的時候,要動態再產生次選單的區域與郵遞區號。用到 ng-change 並放入一個函式 update() 並把選擇到的值傳入函式
ng-change="update(SelCity)
寫下第2層選單內容
$scope.update = function (selectedValue) {
$scope.level2 = selectedValue.areas;
};
其實這樣就可以完成雙層動態下拉選單了。
完整程式碼連結 : http://jsbin.com/iYEdOBI/44/edit