AngularJS set default selected option in dropdown

一笑奈何 提交于 2019-12-25 04:27:30

问题


I am relatively new to AngularJS. Learning every bit of it. I have been worked on KnockoutJS for couple of years and find it comfortable to work on JavaScript.

I am working on a simple Task Manager app which has following JSON as a result on API call for individual task.

{
                      "Id": 1,
                      "title": "Culpa nisi irure qui consectetur non reprehenderit incididunt mollit voluptate culpa enim.",
                      "description" : "test description",
                      "owner": "Hunter Mcdonald",
                      "priority": 1,
                      "isActive": false,
                      "picture": "http://placehold.it/100x100",
                      "registered": "2014-12-29T17:13:33"
                  }

The meaning of priority values is :

1 - High, 0 - Neutral, -1 - Low

The value that I receive from server is strictly in numerical..

However while building the edit form, I want to show these priorities in user understandable text i.e. "High", "Low", "Normal"

I have created array of objects to achieve this -

vm.priorityOptions = [
    { name: "low", value: -1 },
    { name: "normal", value: 0 },
    { name: "high", value: 1 }
];

Now, I want to select default selected priority from the API response I get that is "priority" : 1. Since it is numerical value, I don't know how can I select default selected option in vm.priorityOptions

Any help or helpful snippet on the same?


回答1:


You can use ngOptions directive on <select>:

<select ng-options="item.value as item.name for item in vm.priorityOptions" 
        ng-model="vm.data.priority">
</select>

Here is a working plunker.




回答2:


you can easily achieve this using ng-model

<select ng-model="serverResponse.priority">
       <option ng-repeat="item in priorities" value="{{item.value}}">{{item.name}}</option>
</select>

serverResponse.priority will be automatically selected



来源:https://stackoverflow.com/questions/27633852/angularjs-set-default-selected-option-in-dropdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!