Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save inspirit941/1659dd4fbd7f1ced5fd75cdba88c480b to your computer and use it in GitHub Desktop.
Save inspirit941/1659dd4fbd7f1ced5fd75cdba88c480b to your computer and use it in GitHub Desktop.
Angular file upload directive
<div ng-app="app">
<div ng-controller="UploadController as vm">
<div class="container">
<div class="page-header">
<h1>Angular file upload directive</h1>
<h6>A simple directive to create a customizable file input control.</h6>
</div>
<div class="alert alert-info">
Don't forget to display the console in CodePen to see the uploaded file !
</div>
<form ng-model="vm.file" my-file-upload>
<div class="form-group">
<label for="fileName">Select a file</label>
<div class="input-group">
<input type="text" id="fileName" class="form-control" readonly ng-model="fileName" ng-click="browse()">
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="browse()">Browse</button>
</span>
</div>
</div>
<div>
<button type="reset" class="btn btn-default" ng-click="reset()">Reset</button>
<button type="button" class="btn btn-primary" ng-click="vm.upload()" ng-disabled="!vm.file">Upload</button>
</div>
</form>
</div>
</div>
</div>
var app = angular.module("app", ["myDirectives"]);
var myDirectives = angular.module("myDirectives", []);
app.controller("UploadController", function ($log) {
this.upload = function () {
$log.info("Uploading:", this.file || "no file selected!");
}
})
myDirectives.directive("myFileUpload", function ($compile) {
return {
restrict: "AE",
require: "ngModel",
scope: true,
link: link
};
function link (scope, element, attrs, ngModel) {
var input = angular.element("<input type=\"file\" style=\"display: none;\">");
input.bind("browse", function () {
this.click();
});
input.bind("change", function (changed) {
if (changed.target.files.length < 1) {
return;
}
var fileName = changed.target.files[0].name;
var reader = new FileReader();
reader.onload = function (loaded) {
scope.fileName = fileName;
ngModel.$setViewValue(loaded.target.result);
};
reader.readAsDataURL(changed.target.files[0]);
});
$compile(input)(scope);
element.append(input);
scope.browse = function () {
input.triggerHandler("browse");
};
scope.reset = function () {
scope.fileName = null;
ngModel.$setViewValue(null);
};
}
});
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment