AngularJS <select>问题

Kiw*_*nax 3 javascript angularjs

我有一个奇怪的问题.我在我的应用程序中使用AngularJS,我遇到了标记问题.我有一个控制器,用我的元素处理城市和州:

function MeuController($scope, $http) {  

$scope.states = [];  
$scope.selectedState = '';  

$scope.cities = [];  
$scope.selectedCity = '';  

$http.get('/state/GetStates').success(function(result) {  
    $scope.states = result;  
});  

$scope.getCities = function() {  
    $http.get('/cities/GetCitiesByState?state=' + $scope.selectedState).success(function(result) {  
        $scope.cities = result;  
    });  
}  
});  
Run Code Online (Sandbox Code Playgroud)

在这一点上,一切都很好,易于理解.但...

当我以这种方式创建元素时:

<select class="span2" name="SelectedState" ng-model="selectedState"   
ng-change="getCities()" ng-options="state.ID as state.Name for state in states">  
    <option></option>  
</select>  

<select class="span6" name="SelectedCity" ng-model="selectedCity"  
ng-options="city.ID as city.Name for city in cities">  
    <option></option>  
</select>  
Run Code Online (Sandbox Code Playgroud)

......我的元素没有填充.

如果我这样试试:

<select class="span2" name="SelectedState" ng-model="selectedState"   
ng-change="getCities()">  
    <option ng-repeat="state in states" value="state.ID">{{state.Name}}</option>  
</select>  

<select class="span6" name="SelectedCity" ng-model="selectedCity">  
    <option ng-repeat="city in cities" value="city.ID">{{city.Name}}</option>  
</select>  
Run Code Online (Sandbox Code Playgroud)

现在,值将填充到元素中.虽然,如果我更改"selectedState"范围变量的值,我的元素不会"选择"正确的值?

谁知道为什么?

非常感谢!

max*_*dec 5

好的,实际上问题出在ng-model和之间ng-options.

当你这样做时:

<select class="span6" name="SelectedCity" ng-model="selectedCity"  
ng-options="city.ID as city.Name for city in cities"></select>
Run Code Online (Sandbox Code Playgroud)

然后$scope.selectedCity分配给city.ID而不仅仅是city(检查这个小提琴).

你应该这样写:

<select class="span6" name="SelectedCity" ng-model="selectedCity"  
ng-options="city.Name for city in cities"></select>
Run Code Online (Sandbox Code Playgroud)

检查这个小提琴的结果.

它能解决你的问题吗?