Ângelo Rigo
Ângelo Rigo

Reputation: 2157

Angularjs Dependent State->cities dropdown, retrieve cities from http.get service

I am looking for a way to use an http.get service to retrieve the cities from the federated state they belong. I create a dependent dropdown of cities from a choosen state.

Here is a working fiddle to serve as a base to a dinamic version:

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

I meant to have states and cities:

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

                };
            }

How can i write a factory that receives the state id and adjust to the JSON format: ('Los Angeles': [],'San Francisco': []).

.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>

Upvotes: 1

Views: 5049

Answers (1)

show-me-the-code
show-me-the-code

Reputation: 1553

The factory will fetch the cities by given state and save it in a state->cities map.

.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;
            });
        }
    };
});

You then inject the service into your controller and use that state->cities map to update your 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
}

Upvotes: 2

Related Questions