Valor_ Valor_ - 3 months ago 8
Javascript Question

Autoselect select option based on response with Angular

This is the way my form group for select looks like.

<div class="form-group">
<select class="form-control" ng-model="activeState" >
<option ng-value="0" >No</option>
<option ng-value="1" >Yes</option>

And the response from api i get is
in my current case
{{activeState}} displays 1
. How to handle this with angular that proper select will be automatically selected based on response?

If you need any additional information's please let me know and i will provide. Thank you


The problem is the 0 value which is there in value attribute is string & the value which you got from ajax is 0(number) so that's why when you try to bind a value on load its not working. This can be easily fix by changing doing $scope.activeState = '0';

I'd prefer you to use ng-options directive here which does bind value with object value


<select class="form-control" ng-model="activeState" 
   ng-options="yesNo.value as for yesNo in yesNoOptions">


$scope.yesNoOptions = [
   {name: 'No', value: 0},
   {name: 'Yes', value: 1}
$scope.activeState = 0;

Demo here