Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger click on element dynamically created by AngularJS

I'm using AngularJS to create a new tag in order to download a csv file. Below the code I use to trigger the download. The download starts on Chrome but not in Firefox. Do you have any clue why this happens?

var element = angular.element('<a/>');
element.attr({
   href: exportedString,
   target: '_self',
   download: 'test.csv'
})[0].click();

EDIT: Firefox needs an existent DOM

JS:

var linkElem = $("#link");
var element = angular.element(linkElem);

HTML:

<a ng-hide=true id="link"></a>

EDIT 2: On Chrome, the downloaded file name is "download" and not the passed value ("test.csv" in this case). Any suggestions?

Here there is also a plunker

like image 909
pirata000 Avatar asked Oct 01 '22 18:10

pirata000


1 Answers

This is a bug in Chrome 35 reported in issue #377860.

Follow this answer for more details

I updated your plunker solution.

Basically you need to use it like follow:

var element = document.createElement('a');
var blob = new Blob([$scope.exportContent], {
  type: 'text/csv'
});
var url = URL.createObjectURL(blob);
element.href = url;
element.setAttribute('download', 'test.csv');
document.body.appendChild(element); //Append the element to work in firefox
element.click();
like image 92
nramirez Avatar answered Oct 13 '22 02:10

nramirez