Skip to content

Instantly share code, notes, and snippets.

@omelsoft
Last active September 26, 2017 11:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omelsoft/394a787645c9f66d732cb6aab771e904 to your computer and use it in GitHub Desktop.
Save omelsoft/394a787645c9f66d732cb6aab771e904 to your computer and use it in GitHub Desktop.
AngularJS File Upload using Material Design
angular.module('MyApp')
.controller('AppCtrl', function($scope) {
}).directive('apsUploadFile', apsUploadFile);
function apsUploadFile() {
var directive = {
restrict: 'E',
template: '<input id="fileInput" type="file" class="ng-hide"> <md-button id="uploadButton" class="md-raised md-primary" aria-label="attach_file"> Choose file </md-button><md-input-container md-no-float> <input id="textInput" ng-model="fileName" type="text" placeholder="No file chosen" ng-readonly="true"></md-input-container>',
link: apsUploadFileLink
};
return directive;
}
function apsUploadFileLink(scope, element, attrs) {
var input = $(element[0].querySelector('#fileInput'));
var button = $(element[0].querySelector('#uploadButton'));
var textInput = $(element[0].querySelector('#textInput'));
if (input.length && button.length && textInput.length) {
button.click(function(e) {
input.click();
});
textInput.click(function(e) {
input.click();
});
}
input.on('change', function(e) {
var files = e.target.files;
if (files[0]) {
scope.fileName = files[0].name;
} else {
scope.fileName = null;
}
scope.$apply();
});
}
<div ng-controller="AppCtrl" layout="column" ng-cloak="" ng-app="MyApp">
<md-content layout-padding layout="row" layout-align="start end">
<aps-upload-file></aps-upload-file>
</md-content>
</div>
@omelsoft
Copy link
Author

This was taken from the answers in StackOverflow having a demo in CodePen.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment