Valor_ Valor_ - 5 months ago 15
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">
<label>Active</label>
<select class="form-control" ng-model="activeState" >
<option ng-value="0" >No</option>
<option ng-value="1" >Yes</option>
</select>
</div>


And the response from api i get is
1
or
0
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

Answer

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

Markup

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

Code

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

Demo here

Comments