Angular select with ng-option send index instead of value when submitting form

When I submit a form with Angular selection, it sends the array index of the selected parameter, not its value. I need a string to send, because the server does not know about these indexes. 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 script that the submitted form sends resource=0 , but I want resource='a' . (Note. In my violin, I serialize the form, but this is only to see what it will place. In my application, I actually send to the real endpoint.)

This is similar to this question , but the answer was “don't worry about the meaning”. But in my case, I submit the form, so I'm interested in value. I must be missing something very basic here. Thanks!

+4
source share
4 answers

You should not serialize your form using jquery, since you have all the relevant data in the $ scope field and what you want to serialize (some subsets or some objects that you submit using $ http or $ resources). If you are dead with your approach, create a hidden input with the real name of the data item: 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 would not recommend this, but this is what you want to do.

+6
source

ng-option works with an array. if you want to use make ng-option 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/

+3
source

The simple answer is not posting forms. If you want to use POST data for the endpoint, use $ http or $ resources .

Mark Mark Rajcock's comment on docs: http://docs.angularjs.org/api/ng.directive:select

+1
source

If you still need to solve this problem and use efficient AngularJS methods, this is not applicable, "because you have to rush or require big changes, try this (this worked for me):

 <select id="resourceTemp" ng-model="selectedResource"> <option ng-repeat="r in ['a','b']" value="{{r}}"> {{r}} </option> </select> <input type="hidden" name="resourceTemp" ng-value="selectedResource"> 
0
source

Source: https://habr.com/ru/post/1482848/


All Articles