Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS <select> issues

I'm having a weird problem. I'm using AngularJS in my app and I'm having issues with tag. I have a Controller to have cities and states handled by my elements:

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

At this point, everything is OK and easy to understand. But...

When I create my elements this way:

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

... my elements aren't filled.

If I try this way:

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

Now the values are filled into the elements. Although, if I change the value of "selectedState" scope variable, my element doesn't "select" the right value?

Anyone knows why?

Thank you so much!

like image 655
Kiwanax Avatar asked Jun 25 '26 07:06

Kiwanax


1 Answers

Ok so actually the problem is between ng-model and ng-options.

When you do:

<select class="span6" name="SelectedCity" ng-model="selectedCity"  
ng-options="city.ID as city.Name for city in cities"></select>

Then $scope.selectedCity is assigned to city.ID and not just city (check this fiddle).

You should write it like this:

<select class="span6" name="SelectedCity" ng-model="selectedCity"  
ng-options="city.Name for city in cities"></select>

Check the result in this fiddle.

Does it solve your issue?

like image 106
maxdec Avatar answered Jun 26 '26 20:06

maxdec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!