首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >发布由ng-重复创建的表单数据

发布由ng-重复创建的表单数据
EN

Stack Overflow用户
提问于 2017-10-11 12:11:25
回答 1查看 440关注 0票数 0

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

代码语言:javascript
复制
<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创建的,并且它将是多个的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-11 13:27:08

首先,使用ng模型将输入绑定到模型。然后创建一个将文件输入绑定到模型的指令。最后,从submit按钮调用一个函数,该函数将遍历模型,并为每个文件调用一个上传服务。

代码语言:javascript
复制
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);
      });
    }
  };
});
代码语言:javascript
复制
<!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>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46687908

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档