我的表单中有一个 input type=file 元素。我想创建一个自定义指令,用于在使用输入元素选择文件后立即检查文件大小。我知道如何创建自定义指令,但是在 angularjs 中有什么方法可以确定所选元素的文件大小。不使用 Jquery。
js代码:
app.directive('checkFileSize',function(){
return{
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
// add a parser that will process each time the value is
// parsed into the model when the user updates it.
ctrl.$parsers.unshift(function (value) {
//i want to do something like this
var fileSize= // get file size here
if(fileSize>threshold){
ctrl.$setValidity('checkFileSize',false);
}
// return the value to the model,
return someValue;
});
}
}
});
最佳答案
如何通过指令检查文件大小:
app.directive('checkFileSize',function(){
return{
link: function(scope, elem, attr, ctrl) {
$(elem).bind('change', function() {
alert('File size:' + this.files[0].size);
});
}
}
});
非 jquery 版本:
app.directive('checkFileSize', function() {
return {
link: function(scope, elem, attr, ctrl) {
function bindEvent(element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else {
element.attachEvent('on' + type, handler);
}
}
bindEvent(elem[0], 'change', function() {
alert('File size:' + this.files[0].size);
});
}
}
});
关于javascript - 使用angularjs在上传输入类型=文件之前验证文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25885341/