Skip to content

Instantly share code, notes, and snippets.

@JamsMendez
Last active August 29, 2015 14:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save JamsMendez/d2ef8601e92f5b88c2a5 to your computer and use it in GitHub Desktop.
Save JamsMendez/d2ef8601e92f5b88c2a5 to your computer and use it in GitHub Desktop.
Directiva de Angular.js para Input File y Ajax
// Bootstrap is used for visual effects
/*
HTML
<ng-upload ng-model="file"></ng-upload>
<ng-upload ng-model="Object.file"></ng-upload>
*/
var directives = {
ngUpload: function () {
return {
require: '?ngModel',
restrict: 'E',
template: '<input type="file" class="form-control btn btn-primary">',
link: function(scope, element, attrs, ngModel) {
if (!ngModel) return;
var model = attrs.ngModel;
scope.$watch(model, function (newValue, oldValue) {
if(newValue == null && oldValue != null){
element.children().remove();
element.append('<input type="file" class="form-control btn btn-primary">');
element.children().bind('change', function (event){
var file = event.target.files[0];
if(!(typeof(file) === "undefined")){
// Filter file types
if(file.type == 'application/pdf'){
element.children().removeClass('btn-primary');
element.children().removeClass('btn-danger');
element.children().addClass('btn-success');
scope.$apply(function() {
ngModel.$setViewValue(file);
});
}else{
element.children().removeClass('btn-primary');
element.children().removeClass('btn-success');
element.children().addClass('btn-danger');
scope.$apply(function() {
ngModel.$setViewValue(null);
});
}
}
});
}
})
element.children().bind('change', function (event){
var file = event.target.files[0];
if(!(typeof(file) === "undefined")){
// Filter file types
if(file.type == 'application/pdf'){
element.children().removeClass('btn-primary');
element.children().removeClass('btn-danger');
element.children().addClass('btn-success');
scope.$apply(function() {
ngModel.$setViewValue(file);
});
}else{
element.children().removeClass('btn-primary');
element.children().removeClass('btn-success');
element.children().addClass('btn-danger');
scope.$apply(function() {
ngModel.$setViewValue(null);
});
}
}
});
}
};
}
}
/* HTTP Request Ajax */
http({
headers: { 'Content-Type': undefined },
transformRequest: function (data) {
var formData = new FormData();
var obj_ = angular.toJson(data.obj);
delete obj_.file
formData.append('obj', obj_);
formData.append('file', data.obj.file);
return formData;
},
method: 'POST',
// method: 'PUT',
url: '/foo',
// data: { file: file }
data: { obj: obj }
});
app.directive(directives);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment