Skip to content

Instantly share code, notes, and snippets.

@alexmic
Created July 4, 2013 11:42

Revisions

  1. alexmic created this gist Jul 4, 2013.
    46 changes: 46 additions & 0 deletions directives.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    angular.module('webApp.directives', [])

    // user as file-select="image"
    .directive('fileSelect', ['$q', function($q) {
    return function($scope, $elem, attrs) {
    var openFileInput = function() {
    // gets or creates an input on the DOM.
    var id = '__global_file_input'
    , html = '<input type="file" id="' + id + '" style="display:none" />'
    , input = angular.element('#' + id)
    , deferred = $q.defer();

    if (input.length == 0) {
    input = angular.element(html);
    angular.element('body').append(input);
    }

    // fired when the file input changes.
    var onInputChange = function(event) {
    var files = event.originalEvent.target.files;
    if (files != null && files.length > 0) {
    deferred.resolve(files);
    } else {
    deferred.reject();
    }
    };

    input.bind('change', function(event) {
    $scope.$apply(function() { onInputChange(event); });
    });

    // simulate a click on the input to open the file selector.
    input.trigger('click');

    return deferred.promise;
    };

    $elem.bind('click touchend', function(event) {
    var updateScope = function(files) {
    // uploads only the first image, should be configurable.
    $scope[attrs.fileSelect] = files[0];
    };
    openFileInput().then(updateScope);
    });
    };
    }]);