2015-06-29 65 views
0

我遇到了選擇和你的模型問題。在這個例子中,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爲空。我在另一個視圖中有這個代碼並且工作正常。爲什麼不在這裏?有任何想法嗎 ?

UPDATE 我的狀態源:

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

'usaStates'對象的外觀如何? – nalinc

+0

也可以,你可以分享一個jsfiddle/plnkr嗎? – nalinc

+0

你可以嘗試改變ng-model到一個對象,'ng-model = selectedState.Name'嗎? –

回答

0

大概模型價值沒有得到知識和NG-變化被更早開火。

你可以通過它作爲參數。

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

謝謝,但結果是一樣的。 – ramiromd

0

嘗試傳遞selectedStategetCities(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); 
      }); 
}; 

希望它能幫助。