Angular $ http POST无法绑定数组

时间:2015-08-03 00:21:45

标签: javascript angularjs rest

所以我尝试使用Angular设置帖子功能。我有一个HTML表单,其中有两个文本框(用于用户输入)和一个用于选择多个选项的下拉菜单(因此用户填写表单并将数据提交给服务器)。

绑定两个文本框很好但我不知道如何将我的数组中的两个选项绑定为下拉菜单中的选项?

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

形式:

<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!");
   });
 }
  });

1 个答案:

答案 0 :(得分:1)

您正在尝试将categoryID绑定到您的数组,而您的ngOptions表达式不会遍历您的数组。您需要将categoryId值绑定到其他模型。

categoryID添加模型:

$scope.myForm.categoryId = null;

并更改您的select标记:

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