Whit Waldo
Whit Waldo

Reputation: 5207

Select in form returning name/value array instead of just value

I am attempting to use AngularJS to display three select dropdowns in a form (to indicate a birthday - month, day and year). This form then needs to post these values to my API.

I have an array of each of the months, days and years and I populate the controller like so:

$scope.months = myMonthArray;
$scope.user.birthMonth = $scope.months[0];

$scope.days = myDayArray;
$scope.user.birthDay = $scope.days[0];

$scope.years = myYearArray;
$scope.user.birthYear = $scope.years[0];

$scope.register = function(user) {
  $scope.errors = [];
  repository.register(user).$promise.then(
    function() { $location.url('/'); },
    function(response) { $scope.errors = response.data;});
};

My repository factory method looks like this:

register: function(user) {
  var reg = $resource('/api/registration', null, {
    register: { method: 'POST'}
  });
  return reg.save(user);
}

Finally, the view (for the select looks like the following:

<select id="birthMonth" ng-model="user.birthMonth" ng-options="c.name for c in months"></select>
<select id="birthDay" ng-model="user.birthDay" ng-options="c.name for c in days"></select>
<select id="birthYear" ng-model="user.birthYear" ng-options="c.name for c in years"></select>

The view looks great as each of the select boxes properly populate and show the first value. However, when I submit it, my .NET APT model failed to capture the values - looking at the Fiddler request, it looks like the following:

{"birthMonth":
    {"name":"November","value":11},
  "birthYear":
    {"name":1988,"value":1988},
  "birthDay":
    {"name":23,"value":23}}

All the other fields in the form capture correctly (given that they're just text inputs) so I believe the problem lies in the fact that Angular is providing the array of values rather than simply posting the Value of each select control.

Is it a matter that I'm specifying the model for each of these incorrectly? Or what do I need to be doing differently so it only passes the value of each of these select fields?

Thanks!

Upvotes: 0

Views: 594

Answers (1)

Khanh TO
Khanh TO

Reputation: 48972

With your ng-options expression, you're binding to the whole object. If you need to get only the value field, try:

ng-options="c.value as c.name for c in months"

Your JS could be changed to:

$scope.months = myMonthArray;
$scope.user.birthMonth = $scope.months[0].value;

Do the same for days and years.

Upvotes: 1

Related Questions