Angularjs Dependent State-> cities下拉列表,从http.get服务检索城市

时间:2015-10-07 13:47:52

标签: angularjs drop-down-menu

我正在寻找一种方法来使用http.get服务从他们所属的联合状态中检索城市。我从选择状态创建了一个依赖的城市下拉列表。

这是一个工作小提琴,作为dinamic版本的基础:

http://jsfiddle.net/amrigo/v8u7v4af/

我的意思是拥有州和城市:

function CountryController($scope) {
                $scope.countries = {
                    'Michigan': {
                        'Detroit': [],
                        'Flint': []
                    },
                    'Texas': {
                        'Austin': [],
                        'Houston': []
                    },
                    'California': {
                        'Los Angeles': [],
                        'San Francisco': []
                    }

                };
            }

我如何编写一个接收状态ID并调整为JSON格式的工厂:('洛杉矶':[],'旧金山':[])。

.factory('citiesByState', function($http) {
    return {
        getVersion: function(id) {
            return $http.get('http://www.service.com/ckeck_cities.php')
                            .then(function(response) {
                                return response.data;
            });
        }
    };
});


<select class="form-control input-lg" id="country" ng-model="states" ng-options="country for (country, states) in countries">
    <option value=''>Select</option>
</select>

<select class="form-control input-lg" id="state" ng-disabled="!states" ng-model="cities" ng-options="state for (state,city) in states">
    <option value=''>Select</option>
</select>

1 个答案:

答案 0 :(得分:2)

工厂将按给定状态获取城市并将其保存在州 - >城市地图中。

.factory('citiesByState', function($http) {
    return {
        locationData: {},
        getCities: function(id) {
            var that = this;
            return $http.get('http://www.service.com/ckeck_cities.php?state='+id)
                            .then(function(response) {
                                that.locationData[id] = response.data;
            });
        }
    };
});

然后,您将服务注入您的控制器并使用该州 - >城市地图来更新您的UI。

function CountryController($scope, $citiesByState) {
        $citiesByState.getCities(1); // pass your state id
        $scope.cities = $citiesByState.locationData; //cities will contain your data for the given state when the response is received
}