Created
July 4, 2013 11:42
-
-
Save alexmic/5927005 to your computer and use it in GitHub Desktop.
File select in angular.js.
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 characters
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); | |
}); | |
}; | |
}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment