[英]How to use a single AngularJS directive to display error messages for multiple file inputs
我在單個頁面中有多個文件輸入,如下所示
<input data-file="cancelledCheque" name="cancelledCheque" type="file"
class="fileUpload" ng-file-select="onFileSelect($files)" accept=".jpg,.jpeg">
我的指令如下
App.directive("ngFileSelect", function () {
return {
link: function ($scope, el) {
el.on('click', function () {
this.value = '';
});
el.bind("change", function (e) {
$scope.file = (e.srcElement || e.target).files[0];
var allowed = ["jpeg", "jpg"];
var found = false;
var img;
$scope.filevaliderror = false;
img = new Image();
allowed.forEach(function (extension) {
if ($scope.file.type.match('' + extension)) {
found = true;
$('.filevaliderror').css('display', 'none');
}
});
if (!found) {
//alert('file type should be .jpeg, .jpg');
$('.filevaliderror').css('display', 'block');
return;
}
img.onload = function () {
//var dimension = $scope.selectedImageOption.split(" ");
//if (dimension[0] == this.width && dimension[2] == this.height) {
allowed.forEach(function (extension) {
if ($scope.file.type.match('' + extension)) {
found = true;
$('.filevaliderror').css('display', 'none');
}
});
if (found) {
if ($scope.file.size <= 4194304) {
$scope.getFile();
$('.filevaliderror').css('display', 'none');
} else {
//alert('file size should not be greater then 4 Mb.');
//$scope.file.value = "";
//$scope.filevaliderror = true;
$('.filevaliderror').css('display', 'block');
}
} else {
//alert('file type should be .jpeg, .jpg,');
//$scope.filevaliderror = true;
$('.filevaliderror').css('display', 'block');
}
//} else {
// alert('selected image dimension is not equal to size drop down.');
//}
};
img.src = URL.createObjectURL($scope.file);
});
}
};
現在我面臨的問題是當單個上載出現錯誤時,由於我使用的是類,因此所有輸入都顯示錯誤,所以我應該怎么做才能使用同一指令唯一地顯示錯誤
下面是我的跨度
<span class="filevaliderror" style="padding-top:4px; color:#af0e0e">Upload a valid File</span>
<span class="filevaliderror" style="padding-top:4px;
color:#af0e0e" ng-if="submitted &&
form.cancelledCheque.$error.cancelledCheque">Upload a valid File Error</span>
<span ng-if="submitted && form.cancelledCheque.$error.required">required</span>
您可以將上面的內容更改為僅將錯誤顯示到特定字段。
錯誤元素很難處理,因為它超出了指令的標記范圍。 讓您的指令包裝file input
和error block
如下所示:
<div ng-select-file>
<input type="file"/>
<span ng-show="error">{{error}}"</span>
</div>
然后通過更改范圍的error
屬性來顯示或隱藏錯誤:
link: function ($scope, el) {
el.find('input').bind('change', function (e) {
var file = (e.srcElement || e.target).files[0];
$scope.error = '';
// validate input and show errors...
var isValid = false;
if (!isValid) {
$timeout(function(){
$scope.error = 'Wrong file type';
});
}
});
}
這是做到這一點的有角度的方法。
這里是工作的基本示例: https : //jsfiddle.net/aleckravets/awuLh6gu/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.