I've created a directive to download an audio file. On click of the directive tag, I'm fetching the base64 encoded data from the server and setting the 'href' attribute of the anchor tag(this is the template of the directive) to the fetched data. Then I'm trying to programmatically click the 'a' tag so that the file download popup can be displayed to the user. The problem here is that when the 'click' event is triggered it doesn't do anything but when clicked manually the second time it works.
I've embedded the fiddle code. Any help is really appreciated. Below is the directive code:
angular.module('myTestApp', [])
.directive('webDownloader', downloadFn);
downloadFn.$inject = ['$timeout'];
function downloadFn($timeout) {
function downloadLinkFn(scope, element) {
scope.fileName = scope.fileName || 'test-file';
scope.populateData = function() {
if (scope.dataURL) {
} else {
scope.webProvider()
.then(function (response) {
scope.dataURL =
'data:audio/ogg;base64,' + response;
$timeout(function() {
angular.element(element).
find('a').triggerHandler('click');
}, 0);
});
}
};
// Return the object.
return {
template: '<a data-ng-href="{{dataURL}}" download="{{fileName}}" data-ng-click="populateData()" data-ng-transclude></a>',
transclude: true,
restrict: 'A',
scope: {
fileName: '@',
webProvider: '&'
},
link: downloadLinkFn
};
}
I'm still not sure but if I replace
angular.element(element).find('a').triggerHandler('click');
with
angular.element(element).find('a')[0].click();
it works.
Update:
triggerHandler('click')
doesn't work if href
is not present.So, if I set the default value as scope.dataURL = '#'
, above code will work.