I\'m trying to trigger the click event of the element from the
button
.
I think you are over complicated things a bit. Do you really need to trigger a click on the input from your button ?
I suggest you just apply a proper style to your input and the ngFileSelect directive will do the rest and call your onFileSelect function whenever a file is submitted :
input.file {
cursor: pointer;
direction: ltr;
font-size: 23px;
margin: 0;
opacity: 0;
position: absolute;
right: 0;
top: 0;
transform: translate(-300px, 0px) scale(4);
}
One more directive
html
<btn-file-selector/>
code
.directive('btnFileSelector',[function(){
return {
restrict: 'AE',
template: '<div></div>',
link: function(s,e,a){
var el = angular.element(e);
var button = angular.element('<button type="button" class="btn btn-default btn-upload">Add File</button>');
var fileForm = angular.element('<input type="file" style="display:none;"/>');
fileForm.on('change', function(){
// Actions after the file is selected
console.log( fileForm[0].files[0].name );
});
button.bind('click',function(){
fileForm.click();
});
el.append(fileForm);
el.append(button);
}
}
}]);
best and simple way to use native java Script which is one liner code.
document.querySelector('#id').click();
Just add 'id' to your html element like
<button id="myId1" ng-click="someFunction()"></button>
check condition in javascript code
if(condition) {
document.querySelector('#myId1').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');
};
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');
});
}
};
});
If you are getting $scope binding errors make sure you wrap the click event code on a setTimeout Function.
VIEW
<input id="upload"
type="file"
ng-file-select="onFileSelect($files)"
style="display: none;">
<button type="button"
ng-click="clickUpload()">Upload</button>
CONTROLLER
$scope.clickUpload = function(){
setTimeout(function () {
angular.element('#upload').trigger('click');
}, 0);
};