Skip to content

Instantly share code, notes, and snippets.

@azami
Last active August 29, 2015 14:05
Show Gist options
  • Save azami/ebf0adcd5c04d5c52229 to your computer and use it in GitHub Desktop.
Save azami/ebf0adcd5c04d5c52229 to your computer and use it in GitHub Desktop.
angularjs input type=fileに対応する
.directive('validFile', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
var extentions = /(\.|\/)(gif|jpe?g|png)$/i;
var maxSize = 204800; // bytes
var setViewValue = function(file) {
scope.$apply(function() {
ngModel.$setValidity('extention', extentions.test(file.name));
ngModel.$setValidity('size', file.size <= maxSize);
ngModel.$setViewValue(file);
});
};
element.bind('change', function() {
var reader;
var file = element[0].files[0];
if (file) {
reader = new FileReader();
reader.onload = function() {
file.src = reader.result;
setViewValue(file);
};
reader.readAsDataURL(file);
} else {
setViewValue();
}
});
}
};
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment