1. 程式人生 > >angularjs 實現 三級省市區聯動,可實現無限級聯動

angularjs 實現 三級省市區聯動,可實現無限級聯動

一個select標籤實現省市區三級聯動

html 程式碼:
# 頁面呼叫元件
<select-component ng-repeat="field in data.fieldsList track by $index"
                  options="optionsMap[field]" name="field"
                  change-fun="change(status)"></select-component>
component 程式碼:

angular
    .module("app")
    .component("selectComponent"
, { bindings: { options: "=", name:"=", changeFun:"&", }, template: ` <select ng-change="vm.changeFun({status:{'name':vm.name, 'value':selectVal}})" ng-model="selectVal"> <option value="{{item}}" ng-repeat
="item in vm.options">{{item}}</option> </select> `, controllerAs: "vm", });
// controller程式碼

angular
    .module("app")
    .controller("selectController", [
    "$scope",
    function ($scope) {
        $scope.init = function () {
            $scope.data = {
                areaInfo: {
                    "浙江省"
: { "杭州市": ["西湖區", "餘杭區"], "溫州市": ["開發區", "高開區"] }, "河北省": { "邯鄲市": ["復興區", "邯山區"], "石家莊": ["裕華區", "西城區"] }, "河南省": { "安陽市": ["湯陰區", "開發區"], "鄭州市": ["二金區", "嶺西區"] } }, fieldsList: ["province", "city", "area"], }; }; $scope.init(); $scope.optionsMap = { "province": Object.keys($scope.data.areaInfo), "city": [], "area": [], "selectStatus": {}, }; $scope.change = function (status) { if (status["name"] === "province") { $scope.optionsMap.city = Object.keys($scope.data.areaInfo[status["value"]]); $scope.optionsMap.selectStatus.province = status["value"]; } else if (status["name"] === "city") { var pro = $scope.optionsMap.selectStatus.province; $scope.optionsMap.area = $scope.data.areaInfo[pro][status["value"]]; } }; }]);