I am using Angular JS and I need to set a selected option of a dropdown list control using angular JS. Forgive me if this is ridiculous but I am new with Angular JS
Here is the dropdown list control of my html
<select ng-required="item.id==8 && item.quantity > 0" name="posterVariants"
ng-show="item.id==8" ng-model="item.selectedVariant"
ng-change="calculateServicesSubTotal(item)"
ng-options="v.name for v in variants | filter:{type:2}">
</select>
After it gets populated I get
<select ng-options="v.name for v in variants | filter:{type:2}" ng-change="calculateServicesSubTotal(item)"
ng-model="item.selectedVariant" ng-show="item.id==8" name="posterVariants"
ng-required="item.id==8 && item.quantity > 0" class="ng-pristine ng-valid ng-valid-required">
<option value="?" selected="selected"></option>
<option value="0">set of 6 traits</option>
<option value="1">5 complete sets</option>
</select>
How can I set the control for value="0"
to be selected?
I hope I understand your question, but the ng-model
directive creates a two-way binding between the selected item in the control and the value of item.selectedVariant
. This means that changing item.selectedVariant
in JavaScript, or changing the value in the control, updates the other. If item.selectedVariant
has a value of 0
, that item should get selected.
If variants
is an array of objects, item.selectedVariant
must be set to one of those objects. I do not know which information you have in your scope, but here's an example:
JS:
$scope.options = [{ name: "a", id: 1 }, { name: "b", id: 2 }];
$scope.selectedOption = $scope.options[1];
HTML:
<select data-ng-options="o.name for o in options" data-ng-model="selectedOption"></select>
This would leave the "b" item to be selected.