Reputation: 35968
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
value="R"...
in the HTML$scope.model.selectedcolor
?Upvotes: 1
Views: 96
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
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
Upvotes: 1