Last active
August 29, 2015 14:05
-
-
Save azami/ebf0adcd5c04d5c52229 to your computer and use it in GitHub Desktop.
angularjs input type=fileに対応する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.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