-
-
Save xgrommx/4de6d8becdd0dc909b87 to your computer and use it in GitHub Desktop.
This file contains 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
// 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