themis themis - 1 year ago 61
AngularJS Question

How to set a selected option of a dropdown list control using angular JS

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.quantity > 0" name="posterVariants"
ng-show="" ng-model="item.selectedVariant"
ng-options=" for v in variants | filter:{type:2}">

After it gets populated I get

<select ng-options=" for v in variants | filter:{type:2}" ng-change="calculateServicesSubTotal(item)"
ng-model="item.selectedVariant" ng-show="" name="posterVariants"
ng-required=" &amp;&amp; item.quantity &gt; 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>

How can I set the control for
to be selected?

Answer Source

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:


$scope.options = [{ name: "a", id: 1 }, { name: "b", id: 2 }];
$scope.selectedOption = $scope.options[1];


<select data-ng-options=" for o in options" data-ng-model="selectedOption"></select>

This would leave the "b" item to be selected.