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

9

145

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 &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>
</select>

How can I set the control for value="0" to be selected?

Disjointed answered 31/7, 2013 at 11:12 Comment(1)
<option value="0" ng-selected="true">set of 6 traits</option>Snifter
I
198

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.

Incorporable answered 31/7, 2013 at 11:36 Comment(13)
I have a controler file named order.js, thus the html name the same order.html where the control is. Should I set the selectedVariant there or directly on the control?Disjointed
Usually you would set these things in the controller, on the $scope variable. So assuming you're in a single scope, in your controller you could say $scope.item.selectedVariant = 0, to set the default selected value. You could also set the variable directly on the control, in HTML, using the ng-init directive, but that gets rather messy in my opinion!Coaction
Could you elaborate on what variants is on your scope? You would have to set item.selectedVariant exactly to an item of variants.Coaction
$scope.item.selectedVariant = 0; this will break up the page if I put it in the controler fileDisjointed
can you provide the syntax using ng-init please?Disjointed
I updated my answer with a sample where the data is an array of objects, which I believe your situation is. Hope that helps.Coaction
Please see this plnkr for a working example, and try to retrace the steps!Coaction
you may check out my code please pastebin.com/HdktBk4T and pastebin.com/yEnqEDMcDisjointed
This is what i have been looking for almost two days of combing Stackoverflow. Thank you @stevuuAgnella
Thanks. I have somewhat an extension of this question. If user selects b what should I do to get 2 into my js?Hesperian
@Hesperian Use the "as" operator as described in the docs! It allows you to change what is the value for a given element, for example o.id as o.name for o in options (or o.name as o.id for o in options, depending on what you meant).Coaction
How to do the same if the drop down is a multi select one?Glasgow
what to do if my data-ng-model="formA.selectedOption"?Guff
O
36

I don't know if this will help anyone or not but as I was facing the same issue I thought of sharing how I got the solution.

You can use track by attribute in your ng-options.

Assume that you have:

variants:[{'id':0, name:'set of 6 traits'}, {'id':1, name:'5 complete sets'}]

You can mention your ng-options as:

ng-options="v.name for v in variants track by v.id"

Hope this helps someone in future.

Ollie answered 9/5, 2016 at 17:25 Comment(1)
This is what I was missing! I was setting the scope field that was bound to ngModel properly, but it didn't work until I added the track by! Thank you!Protozoon
L
7

If you assign value 0 to item.selectedVariant it should be selected automatically. Check out sample on http://docs.angularjs.org/api/ng.directive:select which selects red color by default by simply assigning $scope.color='red'.

Loeffler answered 31/7, 2013 at 11:38 Comment(4)
where do I set the item.selectedVariant? if I define $scope.item.selectedVariant = 0; in the controler of the file, angular breaks upDisjointed
could you also paste matching html?Loeffler
I think each item in orderGrid needs to have selectedVariant set to 0Loeffler
can you provide a sample code? I am not familiar with angular sorryDisjointed
H
7

i see here already wrote good answers, but sometime to write the same in other form can be helpful

<div ng-app ng-controller="MyCtrl">
  <select ng-model="referral.organization" ng-options="c for c in organizations"></select>
</div>

<script type='text/javascript'>
  function MyCtrl($scope) {
    $scope.organizations = ['a', 'b', 'c', 'd', 'e'];
    $scope.referral = {
      organization: $scope.organizations[2]
    };
  }
</script>
Heirdom answered 11/10, 2015 at 9:45 Comment(1)
What if I had a drop down that was multi select . Simply setting the ids in the model is not workingGlasgow
Y
2

Simple way

If you have a Users as response or a Array/JSON you defined, First You need to set the selected value in controller, then you put the same model name in html. This example i wrote to explain in easiest way.
Simple example
Inside Controller:

$scope.Users = ["Suresh","Mahesh","Ramesh"]; 
$scope.selectedUser = $scope.Users[0];

Your HTML

<select data-ng-options="usr for usr in Users" data-ng-model="selectedUser">
</select>

complex example
Inside Controller:

$scope.JSON = {
       "ResponseObject":
           [{
               "Name": "Suresh",
               "userID": 1
           },
           {
               "Name": "Mahesh",
               "userID": 2
           }]
   };
   $scope.selectedUser = $scope.JSON.ResponseObject[0];

Your HTML

<select data-ng-options="usr.Name for usr in JSON.ResponseObject" data-ng-model="selectedUser"></select>
<h3>You selected: {{selectedUser.Name}}</h3>    
Yangyangtze answered 22/6, 2016 at 8:46 Comment(0)
S
1

It can be usefull. Bindings dose not always work.

<select id="product" class="form-control" name="product" required
        ng-model="issue.productId"
        ng-change="getProductVersions()"
        ng-options="p.id as p.shortName for p in products">
</select>

For example. You fill options list source model from rest-service. Selected value was known befor filling list and was set. After executing rest-request with $http list option be done. But selected option is not set. By unknown reasons AngularJS in shadow $digest executing not bind selected as it shuold be. I gotta use JQuery to set selected. It`s important! Angular in shadow add prefix to value of attr "value" for generated by ng-repeat optinos. For int it is "number:".

$scope.issue.productId = productId;
function activate() {
   $http.get('/product/list')
     .then(function (response) {
       $scope.products = response.data;

       if (productId) {
           console.log("" + $("#product option").length);//for clarity                       
           $timeout(function () {
               console.log("" + $("#product option").length);//for clarity
               $('#product').val('number:'+productId);
               //$scope.issue.productId = productId;//not work at all
           }, 200);
       }
   });
}
Systematism answered 9/3, 2017 at 15:21 Comment(0)
D
0

Try the following:

JS file

this.options = { 
        languages: [{language: 'English', lg:'en'}, {language:'German', lg:'de'}]
};
console.log(signinDetails.language);

HTML file

<div class="form-group col-sm-6">
    <label>Preferred language</label>
    <select class="form-control" name="right" ng-model="signinDetails.language" ng-init="signinDetails.language = options.languages[0]" ng-options="l as l.language for l in options.languages"><option></option>
    </select>
</div>
Deontology answered 12/1, 2018 at 14:53 Comment(1)
There is already a good solution, that works and has been accepted by OP that it solves his issue.Rider
S
0

This is the code what I used for the set selected value

countryList: any = [{ "value": "AF", "group": "A", "text": "Afghanistan"}, { "value": "AL", "group": "A", "text": "Albania"}, { "value": "DZ", "group": "A", "text": "Algeria"}, { "value": "AD", "group": "A", "text": "Andorra"}, { "value": "AO", "group": "A", "text": "Angola"}, { "value": "AR", "group": "A", "text": "Argentina"}, { "value": "AM", "group": "A", "text": "Armenia"}, { "value": "AW", "group": "A", "text": "Aruba"}, { "value": "AU", "group": "A", "text": "Australia"}, { "value": "AT", "group": "A", "text": "Austria"}, { "value": "AZ", "group": "A", "text": "Azerbaijan"}];
 
 
 for (var j = 0; j < countryList.length; j++) {
      //debugger
      if (countryList[j].text == "Australia") {
          console.log(countryList[j].text); 
          countryList[j].isSelected = 'selected';
      }
      }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<label>Country</label>
<select class="custom-select col-12" id="Country" name="Country"   >
<option value="0" selected>Choose...</option>
<option *ngFor="let country of countryList" value="{{country.text}}" selected="{{country.isSelected}}"   > {{country.text}}</option>
</select>

try this on an angular framework

Salicaceous answered 5/6, 2019 at 4:23 Comment(0)
S
0

JS:

$scope.options = [
  {
    name: "a", 
    id: 1 
  },
  {
    name: "b",
    id: 2 
  }
];
$scope.selectedOption = $scope.options[1];
Scrimp answered 1/8, 2019 at 10:44 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.