【发布时间】:2017-01-17 01:03:31
【问题描述】:
我有一个表格
<div class="form-group">
<input type="file" id="files" file-upload="myFile" ng-disabled="isBig" class="form-control" name="files" />
<output id="list"></output>
</div>
<button type="submit" ng-disabled="isBig" class="btn btn-danger btn-block" ng-click="createUser()">Submit</button>
我有一个将文件绑定到范围的自定义指令,在此指令中,我创建图像对象并在 onload 方法中检查文件大小。如果文件大小大于指定限制,我想取消选择文件,禁用表单提交按钮并提醒用户选择较小尺寸的图像。如果大小更大,我尝试将 onload 方法中的范围属性设置为 true,但它不起作用。
app.directive('fileUpload', ['$parse',
function($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileUpload);
var modelSetter = model.assign;
element.bind('change', function() {
scope.$apply(function() {
if (element[0].files.length > 1) {
modelSetter(scope, element[0].files);
} else {
modelSetter(scope, element[0].files[0]);
var file = element[0].files[0];
if (file) {
var img = new Image();
img.src = window.URL.createObjectURL(file);
img.onload = function() {
var width = img.naturalWidth,
height = img.naturalHeight;
window.URL.revokeObjectURL(img.src);
var isBig = false;
if (width <= 200 && height <= 200) {
modelSetter(scope, isBig);
} else {
isBig = true;
modelSetter(scope, isBig);
}
};
}
}
});
});
}
};
}
]);
任何关于我不正确的地方都将不胜感激。
【问题讨论】:
标签: javascript jquery html angularjs forms