2015-10-07 31 views
1

我正在寻找一种方法来使用http.get服务从它们所属的联邦状态中检索城市。我从一个选定的州创建了一个依赖城市的下拉菜单。Angularjs依赖州 - >城市下拉,从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格式:('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> 
+1

什么状态ID?数据不包含任何ID属性。如果您使用嵌套数组而不是嵌套对象,可能会更简单 – charlietfl

+0

您的意思是这种格式:? '''''''''''''','stateName':'Michigan':{'id':'1','name':'底特律'}, {'id':' '''','name':'Flint'} }, 'id':'2','stateName':'Texas':{'id':'3','name':'Austin' }, {'id':'4','name':'Houston'} }, 'id':'3','stateName':'California':{'id':'5' ,'name':'Los Angeles'}, {'id':'6','name':'San Francisco'} } };' –

+1

close,但这不是有效的结构,数组 – charlietfl

回答

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 
} 
+0

如何将结果数据传递给模板?并将变量,如id和名称绑定到选择框?它能以这种格式吗? ''Michigan':[ {'id':'1','name':'Detroit'}, {'id':'2','name':'Flint'} ], 'Texas ':['id':'3','name':'Austin'}, {'id':'4','name':'Houston'} ]' '