选择不与模型绑定

时间:2015-06-29 06:29:44

标签: angularjs combobox angular-ngmodel

我遇到了一个选择和你的模型的问题。在此示例中,usaStates是存储在根范围中的对象数组。

<label>State:</label>
<select name="state" ng-model="selectedState" ng-options="state.name for state in usaStates" required ng-change="getCities()">
    <option>Select a state</option>
</select>

所以,在我的控制器里我有:

$scope.selectedState = null;
$scope.getCities = function()
{
   console.log($scope.selectedState);
   var stateCode = $scope.selectedState.id;
   MainService.getCities(stateCode)
   .then(function(httpData){
      $scope.cities = httpData.data;
   })
   .catch(function(error){
      console.log(error);
   });
};

选择状态时,会触发getCities函数,但$scope.selectedState为空。我在另一个视图中有这个代码,并且工作正常。为什么不在这里?有什么想法吗?

更新 我的州政府来源是:

[{id: "AL", name: "Alabama"}, {id: "AK", name: "Alaska"}, {id: "AZ", name: "Arizona"},…]

2 个答案:

答案 0 :(得分:0)

模型值可能不会获得知识,而且ng-change会被提前解雇。

您可以将其作为参数传递。

<select name="state" ng-model="selectedState" ng-options="state.name for state in usaStates" required ng-change="getCities(selectedState)">
    <option>Select a state</option>
</select>

在控制器中。

$scope.selectedState = null;
$scope.getCities = function(selectedState)
{
   console.log(selectedState);
   var stateCode = selectedState.id;
   MainService.getCities(stateCode)
   .then(function(httpData){
      $scope.cities = httpData.data;
   })
   .catch(function(error){
      console.log(error);
   });
};

答案 1 :(得分:0)

尝试将selectedState传递给getCities(selectedState)函数。

<强> E.g。

<强> HTML

<select name="state"
        ng-model="selectedState" 
        ng-options="state.name for state in usaStates" 
        ng-change="getCities(selectedState)"
        required="required">
    <option>Select a state</option>
</select>

<强> JS

$scope.selectedState = null;
$scope.getCities = function(selectedState) {
    $scope.selectedState = selectedState;
    console.log($scope.selectedState);
    var stateCode = $scope.selectedState.id;
    MainService.getCities(stateCode)
            .then(function(httpData) {
                $scope.cities = httpData.data;
            })
            .catch(function(error) {
                console.log(error);
            });
};

希望它有所帮助。