When I post a form with an Angular select, it sends the array index of the selected option, not its value. I need the string to be sent because the server doesn't know about these indices. How can I fix this?
From jsfiddle.net/2SuZG:
<form method="post" action="/my/post/endpoint">
<select name="resource" ng-options="r for r in ['a', 'b']"
ng-model="selectedResource"></select>
<button type="submit">Save</button>
</form>
You can see from the console output in the fiddle that the posted form is sending resource=0
, but I want resource='a'
. (Note: In my fiddle, I am serializing the form, but this is only to see what it would be posting. In my app I am actually posting to a real endpoint.)
This is similar to this question, but the answer there was "don't worry about the value". But in my case, I am posting a form so I am concerned with the value. I must be missing something very basic here. Thanks!
You shouldn't be serializing your form with jquery since you have all of the pertinent data in the $scope and that's what you'd want to serialize (some subset or some object that you'd be posting with $http or $resource). If you are dead set with your approach, create a hidden input with the real name of the data element: http://jsfiddle.net/2SuZG/1/
<select name="resourceTemp" ng-options="r for r in ['a', 'b']"
ng-model="selectedResource"></select>
<input type="hidden" name="resource" value="{{selectedResource}}" >
I wouldn't recommend this but it is what you'll want to do.
ng-option works on array. if you want to use ng-option make array like this
r = [{ "value": 1, "text": "a" }, { "value": 2, "text": "v" }];
<select ng-option="obj.value as obj.text for obj in r">
Or you can use ng-repeat in your case
<form method="post">
<select name="resourceTemp" ng-model="selectedResource">
<option ng-repeat="r in ['a','b']" value="{{r}}">{{r}}</option>
</select>
<input type="hidden" name="resource" value="{{selectedResource}}" >
<button type="submit">Save</button>
</form>
http://jsfiddle.net/nHyET/
The simple answer is to not post forms. If you want to POST
data to an endpoint, use $http or $resource.
Check out Mark Rajcok's comment on the docs: http://docs.angularjs.org/api/ng.directive:select
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With