I'm trying to trigger the click event of the <input type="file">
element from the button
.
<input id="upload"
type="file"
ng-file-select="onFileSelect($files)"
style="display: none;">
<button type="button"
ng-click="angular.element('#upload').trigger('click');">Upload</button>
It's common practice to hide the uglified beast known as <input type=file>
and trigger it's click event by some other means.
The syntax is the following: function clickOnUpload() { $timeout(function() { angular. element('#myselector'). triggerHandler('click'); }); }; // Using Angular Extend angular.
Another significant difference between ng-click and onclick is the execution context. Code inside an onclick attribute executes against the global window object, while an expression inside of ng-click executes against a specific scope object, typically the scope object representing the model for the current controller.
The ng-click directive tells AngularJS what to do when an HTML element is clicked.
If your input and button are siblings (and they are in your case OP):
<input id="upload"
type="file"
ng-file-select="onFileSelect($files)"
style="display: none;">
<button type="button" uploadfile>Upload</button>
Use a directive to bind the click of your button to the file input like so:
app.directive('uploadfile', function () {
return {
restrict: 'A',
link: function(scope, element) {
element.bind('click', function(e) {
angular.element(e.target).siblings('#upload').trigger('click');
});
}
};
});
So it was a simple fix. Just had to move the ng-click
to a scope click handler:
<input id="upload"
type="file"
ng-file-select="onFileSelect($files)"
style="display: none;">
<button type="button"
ng-click="clickUpload()">Upload</button>
$scope.clickUpload = function(){
angular.element('#upload').trigger('click');
};
I had this same issue and this fiddle is the shizzle :) It uses a directive to properly style the file field and you can even make it an image or whatever.
http://jsfiddle.net/stereosteve/v5Rdc/7/
/*globals angular:true*/
var buttonApp = angular.module('buttonApp', [])
buttonApp.directive('fileButton', function() {
return {
link: function(scope, element, attributes) {
var el = angular.element(element)
var button = el.children()[0]
el.css({
position: 'relative',
overflow: 'hidden',
width: button.offsetWidth,
height: button.offsetHeight
})
var fileInput = angular.element('<input type="file" multiple />')
fileInput.css({
position: 'absolute',
top: 0,
left: 0,
'z-index': '2',
width: '100%',
height: '100%',
opacity: '0',
cursor: 'pointer'
})
el.append(fileInput)
}
}
})
<div ng-app="buttonApp">
<div file-button>
<button class='btn btn-success btn-large'>Select your awesome file</button>
</div>
<div file-button>
<img src='https://www.google.com/images/srpr/logo3w.png' />
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With