Skip to content

Instantly share code, notes, and snippets.

@coreypnorris
Last active December 20, 2016 23:08
Show Gist options
  • Select an option

  • Save coreypnorris/21ffebde2db6772fcfd225220aa7ddaa to your computer and use it in GitHub Desktop.

Select an option

Save coreypnorris/21ffebde2db6772fcfd225220aa7ddaa to your computer and use it in GitHub Desktop.
Custom directive for uploading files with material design styling.

GitHub Logo

Installation

  • Run yeoman command yo angular:directive apsUploadFile
  • Create the html template file app\views\directives\apsuploadfile.html
<input id="apsFileInput" type="file" class="ng-hide">

<md-button id="apsUploadButton" class="md-raised md-primary" aria-label="attach_file">
  Choose file
</md-button>

<md-input-container md-no-float>
  <input id="apsTextInput" ng-model="fileName" type="text" placeholder="No file chosen" ng-readonly="true">
</md-input-container>
  • Replace the code in the app\scripts\directives\apsuploadfile.js file
'use strict';

/**
 * @ngdoc directive
 * @name addressBookApp.directive:apsUploadFile
 * @description
 * # apsUploadFile
 */
angular.module('addressBookApp')
  .directive('apsUploadFile', function () {
    return {
      templateUrl: 'views/directives/apsuploadfile.html',
      restrict: 'E',
      link: function postLink(scope, element, attrs) {
        var input = $(element[0].querySelector('#apsFileInput'));
        var button = $(element[0].querySelector('#apsUploadButton'));
        var textInput = $(element[0].querySelector('#apsTextInput'));

        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();
        });
      }
    };
  });
  
  // NOTE: Replace all instances 'addressBookApp' with the name of your angular app

Usage

<aps-upload-file></aps-upload-file>

Resources

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