Created
July 4, 2013 11:42
Revisions
-
alexmic created this gist
Jul 4, 2013 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal 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); }); }; }]);