我有一个输入字段=、一个复选框和一个文件上传选项,每行表都是由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创建的,并且它将是多个的。
发布于 2017-10-11 13:27:08
首先,使用ng模型将输入绑定到模型。然后创建一个将文件输入绑定到模型的指令。最后,从submit按钮调用一个函数,该函数将遍历模型,并为每个文件调用一个上传服务。
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>
https://stackoverflow.com/questions/46687908
复制相似问题