1

Starting out on Angular and using select dropdowns are really confusing me. Basically I am getting JSON object using an AJAX call and then populating my form with JSON using AngularJS.

For the dropdown, the settings.metric = '2' from database. So the selected is "cm".

My question is, how do I get the currently selected option and its datavalue? I tried scope.settings.metric but all that gives me is "2". I like to get the other properties of the selected such as name and datavalue.

$scope.metrics = [
            {id:1,name:'in',value:'1',datavalue:'in'},
            {id:2,name:'cm',value:'2',datavalue:'cm'},
            {id:3,name:'px',value:'3',datavalue:'px'},
            {id:4,name:'pt',value:'4',datavalue:'pt'}
            ];

<select 
    ng-model="settings.metric" // this is 2 from database call
    ng-options="p.value as p.name for p in metrics" >
</select>
0

1 Answer 1

5

This is pretty simple with what you already have. You have to write this.

ng-options="p as p.name for p in metrics"

The first parameter 'p' is the value that will be stored. The second parameter 'p.name' is the value displayed in the option.

Sign up to request clarification or add additional context in comments.

7 Comments

Hi, thanks for answer. But I was wondering how to access the currently selected option properties from outside in another javascript function... any ideas?
check the value of the ng-model
@ScottYu-UXdesigner If you do it this way you have the whole object in scope.settings.metric
@ZackArgyle Thats weird.. I tried doing scope.settings.metric but all I get is "2"... I finally had to do scope.metrics[parseFloat(scope.settings.metric-1)].datavalue;
@ScottYu-UXdesigner, Don't know how you are doing it, but here is a fiddle that seems to be working fine with your stuff. jsFiddle Example
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.