触发单击AngularJS动态创建的元素

时间:2022-10-22 07:53:11

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?

我正在使用AngularJS创建一个新标签,以便下载csv文件。我用来触发下载的代码下面。下载从Chrome开始,但不在Firefox中。你知道为什么会这样吗?

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

EDIT: Firefox needs an existent DOM

编辑:Firefox需要一个现有的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?

编辑2:在Chrome上,下载的文件名是“下载”而不是传递的值(在本例中为“test.csv”)。有什么建议?

Here there is also a plunker

这里还有一个plunker

2 个解决方案

#1


5  

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

这是问题#377860中报告的Chrome 35中的错误。

Follow this answer for more details

请按照此答案了解更多详情

I updated your plunker solution.

我更新了你的plunker解决方案。

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();

#2


0  

To get both Chrome & FF to work, I actually found that I had to first check to see if element[0] was undefined (which it was in Chrome but not FF):

为了让Chrome和FF都能正常工作,我实际上发现我必须首先检查元素[0]是否未定义(它是在Chrome中但不是FF):

var link = $("#reportDownloadLink");
var element = angular.element(link)
    .attr('href', dataUrl)
    .attr('download', data.FileDownloadName)
    .attr('target', '_blank');
(element[0] || element).click();

#1


5  

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

这是问题#377860中报告的Chrome 35中的错误。

Follow this answer for more details

请按照此答案了解更多详情

I updated your plunker solution.

我更新了你的plunker解决方案。

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();

#2


0  

To get both Chrome & FF to work, I actually found that I had to first check to see if element[0] was undefined (which it was in Chrome but not FF):

为了让Chrome和FF都能正常工作,我实际上发现我必须首先检查元素[0]是否未定义(它是在Chrome中但不是FF):

var link = $("#reportDownloadLink");
var element = angular.element(link)
    .attr('href', dataUrl)
    .attr('download', data.FileDownloadName)
    .attr('target', '_blank');
(element[0] || element).click();