Anthony
Anthony

Reputation: 35968

How to bind, populate, and fetch selected value on submit of <select> with AngularJS

I have a JSON object on the scope that looks like this:

  $scope.colors = [
    {'colorCode': 'R', 'colorName': 'Red'},
    {'colorCode': 'Y', 'colorName': 'Yellow'},
    {'colorCode': 'P', 'colorName': 'Pink'},
  ];

I would like to bind a <select> to this so that it looks like this

<select>
   <option value="R">Red</option>
   <option value="Y">Yellow</option>
   <option value="P">Pink</option>
</select>

What I've done is this:

<select
   ng-model="model.selectedcolor"
   ng-options="c.colorCode as c.colorName for c in colors">
</select>

However, when I inspect the html it is creating HTML like this:

<select>
   <option value="0">Red</option>
   <option value="1">Yellow</option>
   <option value="2">Pink</option>
</select>

Questions

  1. How can I pre-select the second item in the drop down (in this case, Yellow)
  2. How can I have value="R"... in the HTML
  3. When I submit the form, will I be able to get the selected value by $scope.model.selectedcolor?

Upvotes: 1

Views: 96

Answers (2)

New Dev
New Dev

Reputation: 49590

ng-options is arguably a better alternative than ng-repeat-ing <option>. This is because the ng-model can be bound to an object (of the value as value).

You have specified it correctly.

Angular would, under the covers, properly map the selected <option> value to the right object for you, and you don't even need to care about what the value attribute of <option> is set to - this is to answer your question #2.

On question #1, to (pre-)select an option, modify the ng-model-bound property accordingly. This will "drive" the View. In your case, set:

$scope.model.selectedcolor = "Y";

On question #3, it depends on what you mean by "submit a form". You typically don't classically submit a form to the server with an SPA (another reason, why you shouldn't care about that <option value="1"> for "Y"). $scope.model.selectedcolor will be set to the selected colorcode.

As an off-topic:

You could bind your select to the actual color object, and not just the colorcode property:

<select ng-model="model.selectedColor"
        ng-options="c as c.colorName for c in colors">
</select>

Then, you can operate with the entire object. For example, to preselect and to submit, you would do:

$scope.model.selectedColor = $scope.colors[1]; // second one is selected

$scope.submit = function(){
   var colorcode = $scope.model.selectedColor.colorcode;
   // post colorcode to server
}

Upvotes: 1

mohamedrias
mohamedrias

Reputation: 18566

To populate your select:

<select ng-model="model.selectedcolor"  ng-options="color.colorCode as color.colorName for color in colors" >

</select> 

In your controller:

To preselect:

$scope.model = {
     selectedcolor : "Y"
}

When you submit:

Try accessing:

$scope.model.selectedcolor

It will give you Y

DEMO

DEMO WITH SUBMIT

Upvotes: 1

Related Questions