Post 由 ng-repeat 创建的表单数据

Post data of form created by ng-repeat

我在 table 的每一行有一个输入字段 =、一个复选框和一个文件上传选项,这些行是由 ng-repeat 创建的。

<tr data-ng-repeat="choice in choices track  by $index">
<td><input type="textbox" size="50" class="des-textinput" required></td>
<td><input type="checkbox" required></td>
<td><input type="file" class="photo-upload" ></td>
</tr>

我的问题是如何通过 ng-repeat 创建的一个提交按钮 post 数据到后端,并且它将是多个。

对于初学者来说,使用 ng-model 将您的输入绑定到模型。然后创建一个将文件输入绑定到模型的指令。最后,从您的提交按钮调用一个函数,该函数将遍历模型并为每个文件调用上传服务。

var app = angular.module('uploadApp', []);

app.controller('MainCtrl', function($scope) {
  $scope.choices = [{
    desc: 'file 1',
    include: false,
    file: null
  }, {
    desc: 'file 2',
    include: false,
    file: null
  }, {
    desc: 'file 3',
    include: false,
    file: null
  }];

  $scope.uploadFiles = function() {
    $scope.choices.forEach(f => {
      const file = f.file;
      if (file) {
        // call upload function from here
        console.log('Upload: ', file);
      }
    });
  };
});

app.directive("fileInput", function() {
  return {
    require: "ngModel",
    restrict: 'A',
    link: function postLink(scope, element, attrs, ngModel) {
      element.on("change", function(e) {
        var file = element[0].files[0];
        ngModel.$setViewValue(file);
      });
    }
  };
});
<!DOCTYPE html>
<html ng-app="uploadApp">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>
</head>

<body ng-controller="MainCtrl">
  <table>
    <tr data-ng-repeat="choice in choices track  by $index">
      <td>
        <input type="textbox" size="50" class="des-textinput" ng-model="choice.desc" required />
      </td>
      <td>
        <input type="checkbox" required ng-model="choice.include" />
      </td>
      <td>
        <input type="file" class="photo-upload" ng-model="choice.file" file-input/>
      </td>
    </tr>
  </table>
  <button ng-click="uploadFiles()">Submit</button>
</body>

</html>