我的表单中有一个input type = file元素。我想使用input元素选择文件时创建一个自定义指令来检查文件大小。我知道如何创建一个创建自定义指令,但是在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;
});
}
}
});
答案 0 :(得分:8)
如何从指令检查文件大小:
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);
});
}
}
});