How can I trigger the click event of another element in ng-click using angularjs?
Solution 1:
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');
});
}
};
});
Solution 2:
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');
};
Solution 3:
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>