我有一个输入字段=,每行一个复选框和一个文件上传选项,行由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
创建的一个提交按钮将数据发布到后端,它将是多个。
答案 0 :(得分:0)
首先,使用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);
});
}
};
});
&#13;
<!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>
&#13;