Search code examples
angularjsng-options

AngularJS set default selected option in dropdown


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"

enter image description here

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?


Solution

  • 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.