Javascript - 为什么这个可靠的下拉列表的Angular JS代码不起作用?

时间:2017-04-16 15:23:17

标签: javascript html angularjs json

我正在尝试使用AngularJS实现乡村城市可靠的下拉列表

<div>
        Country:
        </br>
        <select data-ng-model="country" ng-options="country.name for country in countries" data-ng-change="updateCountry(country)">
            <option value="">Select country</option>
        </select>
    </div>
    <div>
        City</br>
        <select data-ng-model="city" data-ng-options="city.name for city in countryItem">
            <option value="">Select city</option>
        </select>
    </div>

控制器代码

   $scope.updateCountry = function(selectedCountry)
    {
        console.log("The selected country is 
"+JSON.stringify(selectedCountry));

        HomeFactory.setTappedCountryData(selectedCountry);

        $scope.countryItem = HomeFactory.getTappedCountryData();

        console.log("The country Item is "+JSON.stringify($scope.countryItem));
    }

工厂代码

function setTappedCountryData(data){      
    console.log(JSON.stringify(data));       
    selectedCountry = data;       
};


  function getTappedCountryData(data){         
        console.log(JSON.stringify(data));      
    return selectedCountry;       
};

JSON数据

[{
        "id": "1", "name":"USA",
            "cities": [{
            "id": "1",
                "name": "New York"
        }, {
            "id": "2",
                "name": "Los Angeles"
        }]
    }, {
        "id": "2", "name":"UK",
            "cities": [{
            "id": "3",
                "name": "London"
        }, {
            "id": "4",
                "name": "Glasgow"
        }]
    },
    {
        "id": "3", "name":"Russia",
            "cities": [{
            "id": "5",
                "name": "Moscow"
        }, {
            "id": "6",
                "name": "St. Petersburg"
        }]
    },
    {
        "id": "4", "name":"Spain",
            "cities": [{
            "id": "7",
                "name": "Madrid"
        }, {
            "id": "8",
                "name": "Barcelona"
        }]
    },
    {
        "id": "5", "name":"India",
            "cities": [{
            "id": "9",
                "name": "Delhi"
        }, {
            "id": "10",
                "name": "Mumbai"
        }]
    }]

我无法在第二次下拉列表中获得特定国家/地区的城市数量。我在哪里弄错了?

Hadi Jeddizahed解决了这个问题

唯一的问题是代码无法在Chrome开发者移动模拟器中运行(适用于iphone6,Nexus 6等移动设备)

1 个答案:

答案 0 :(得分:1)

试试这样。 您也可以通过简单的方式在控制器中执行此操作

 $scope.updateCountry = function(selectedCountry) {
    $scope.countryItem = selectedCountry.cities
 }

和视图类似

 <select data-ng-model="city" data-ng-options="city.name for city in country.cities">
        <option value="">Select city</option>
 </select>

DEMO