简体   繁体   中英

Angular.js: set default selected from ID

I have an angular.js single page app, with initial data gathered from a rest endpoint.

This app gets a list of IDs representing a saved models, as well as a tree of options to populate some cascading dropdowns.

How can I set the default path in the tree based on my IDs from the model?

Some illustrative code:

Models:

DefaultOptions = [
    {"Id" : 044},
    {"Id" : 142},
    {"Id" : 244}
];

OptionsTree = [
    {"Text" : "Option1",
     "subOptions" : [
          {"Text" : "SubOption1", "Id" : 044},
          {"Text" : "SubOption2", "Id" : 142}
      ]},
    {"Text" : "Option2",
     "subOptions" : [
          {"Text" : "SubOptionA", "Id" : 3033},
          {"Text" : "SubOptionB", "Id" : 244}
      ]}
];

HTML:

<div ng-repeat="member in DefaultOptions">
    <select ng-model="option" 
            ng-options="o as o.Text for o in OptionsTree">
    </select>

    <select ng-model="subOption" 
            ng-options="s as s.Text for s in option.subOptions"
            ng-disabled="!option" 
            ng-change="member.Id = subOption.Id">
    </select>
</div>

This HTML will properly update the DefaultOptions ID if the user selects a new one, but cannot set the default. What am I missing?

Change your selects' ng-model to account for the ng-repeat :

Then put this in your controller:

// Main dropdown
$scope.member.option = OptionsTree[0];

and then:

// Sub dropdown
$scope.member.subOption = OptionsTree[0].subOptions[0].id

Since your question didn't state if you wanted the id or the whole object I assumed the whole object for the main dropdown and just the id for the sub dropdown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM