144

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?

Nikhil Sahu
  • 2,463
  • 2
  • 32
  • 48
themhz
  • 8,335
  • 21
  • 84
  • 109

9 Answers9

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.

Steve Klösters
  • 9,427
  • 2
  • 42
  • 53
  • 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? – themhz Jul 31 '13 at 11:40
  • 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](http://docs.angularjs.org/api/ng.directive:ngInit) directive, but that gets rather messy in my opinion! – Steve Klösters Jul 31 '13 at 11:43
  • Could you elaborate on what `variants` is on your scope? You would have to set `item.selectedVariant` exactly to an item of `variants`. – Steve Klösters Jul 31 '13 at 11:47
  • $scope.item.selectedVariant = 0; this will break up the page if I put it in the controler file – themhz Jul 31 '13 at 11:48
  • can you provide the syntax using ng-init please? – themhz Jul 31 '13 at 11:48
  • I updated my answer with a sample where the data is an array of objects, which I believe your situation is. Hope that helps. – Steve Klösters Jul 31 '13 at 11:52
  • Please see this [plnkr](http://plnkr.co/edit/2COBn7Pl5J9LOyNI6tba?p=preview) for a working example, and try to retrace the steps! – Steve Klösters Jul 31 '13 at 12:19
  • you may check out my code please http://pastebin.com/HdktBk4T and http://pastebin.com/yEnqEDMc – themhz Jul 31 '13 at 13:30
  • This is what i have been looking for almost two days of combing Stackoverflow. Thank you @stevuu – David Addoteye Nov 03 '14 at 19:05
  • Thanks. I have somewhat an extension of this question. If user selects b what should I do to get 2 into my js? – yalkris May 20 '15 at 23:01
  • @yalkris Use the "as" operator as described in [the docs](https://docs.angularjs.org/api/ng/directive/ngOptions)! 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). – Steve Klösters May 21 '15 at 10:46
  • How to do the same if the drop down is a multi select one? – Nikhil Sahu Aug 24 '16 at 18:33
  • what to do if my data-ng-model="formA.selectedOption"? – Akhilesh Kumar Oct 07 '16 at 08:24
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.

akmozo
  • 9,829
  • 3
  • 28
  • 44
jsmtslch
  • 708
  • 7
  • 19
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'.

T W
  • 6,267
  • 2
  • 26
  • 33
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>
Arthur Tsidkilov
  • 5,401
  • 2
  • 21
  • 18
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>    
shreedhar bhat
  • 4,779
  • 1
  • 18
  • 23
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);
       }
   });
}
georgeawg
  • 48,608
  • 13
  • 72
  • 95
trueboroda
  • 2,650
  • 26
  • 24
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>
Asha Joshi
  • 87
  • 8
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

karel
  • 5,489
  • 46
  • 45
  • 50
0

JS:

$scope.options = [
  {
    name: "a", 
    id: 1 
  },
  {
    name: "b",
    id: 2 
  }
];
$scope.selectedOption = $scope.options[1];
Hawz
  • 4,027
  • 1
  • 10
  • 11
Snehal S
  • 34
  • 4