How to set a selected option of a dropdown list co

2019-01-01 15:37发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

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\'.



回答4:

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>


回答5:

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);
                   }
               });
}


回答6:

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>    


回答7:

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>