Whirlwind990
Whirlwind990

Reputation: 99

Angular $http POST unable to bind array

So I'm trying to set up a post function using Angular. I've got a HTML form which has two text boxes (for user input) and a drop down menu for selecting a number of choices (so the user fills out the form and submits data to server).

Binding the two text boxes is fine but I don't know how to bind the two options in my array as choices in the drop down menu?

(Heres a fiddle:http://jsfiddle.net/gtv7s8h3/2/ )

Form:

<form>
<input type="text" id="name" ng-model="myForm.Title" ng-minlength="5" ng-maxlength="20"> title <br/>
<input type="text" id="name" ng-model="myForm.Content" ng-minlength="5" ng-maxlength="20"> content <br />

<select ng-model="CategoryId" ng-options="item.name for item in CategoryId"></select>

<button ng-click="myForm.submitTheForm()">Submit Form</button>
</form>

Angular POST:

 angular.module("myapp", [])
 .controller("MyController", function($scope, $http) {
  $scope.myForm = {};
  $scope.myForm.Title = "";
  $scope.myForm.Content = "";
  $scope.CategoryId = {
    data: [{
        id: '316556404cac4a6bb47dd4c7ca2dac4a',
        name: 'name1'
    }, {
        id: '306e3d9a6265480d94d0d50e144435f9',
        name: 'name2'
    }]
  };       

 $scope.myForm.submitTheForm = function(item, event) {
 var dataObject = {
 Title : $scope.myForm.Title,
 Content : $scope.myForm.Content,
 CategoryId : $scope.CategoryId 

   };

   var responsePromise = $http.post("/url", dataObject, {});
   responsePromise.success(function(dataFromServer, status, headers, config) {
      console.log(dataFromServer.title);
   });
    responsePromise.error(function(data, status, headers, config) {
      alert("Submitting form failed!");
   });
 }
  });

Upvotes: 1

Views: 82

Answers (1)

logee
logee

Reputation: 5067

You're trying to bind the categoryID to you array and your ngOptions expression does not loop through your array. You need to bind the categoryId value to a different model.

Add a model for your categoryID:

$scope.myForm.categoryId = null;

and change your select markup:

<select ng-model="myForm.categoryId" ng-options="item.id as item.name for item in CategoryId.data"></select>

Upvotes: 1

Related Questions