2017-10-11 30 views
0

我有一個輸入字段=,每行表格有一個複選框和一個文件上傳選項,行由ng-repeat創建。由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> 

我的問題是如何發佈DATAS通過一個後端,因爲它是由ng-repeat創建提交按鈕,這將是多個。

回答

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); 
 
     }); 
 
    } 
 
    }; 
 
});
<!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="[email protected]" 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>