我试图设置一个按钮或锚点,将一些文本下载到.txt文件中。使用Jquery,我做一个简单的$('#copy_Output_logs')。text();和我的文本在我的控制台中正确。所以我设置了href链接,但我一直收到一个空白文件。对于我的描述,由于我的文本在点击时动态加载,这不会起作用。
所以我创建了一个可以在点击时执行的功能。但我的主持人用这个奇怪的网址"http://localhost:8080/%7B%7B"
打开一个页面。通过在按钮上设置un-ng-click但尝试下载对话框(我需要)来尝试替换方法,它只是重定向到带有文本的页面。
到目前为止,这是我的代码:
App.controller('Forumlaire_Controller', function ($scope, Shared_Service) {
$scope.Download = function() {
return Shared_Service.Service_download();
}
})
.config( function($compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(|blob|):/);
});
App.factory('Shared_Service', function($q) {
return {
Service_download: function() {
var url = $window.URL || $window.webkitURL;
var data = $('#copy_Output_logs').text();
console.log($('#copy_Output_logs').text()) // On ng-click the text showup correctly
console.log(url.createObjectURL(new Blob([data], { type: 'text/plain' }))); //Via ng-click the url generates correctly in the console.
return url.createObjectURL(new Blob([data], { type: 'text/plain' }));
}
}
});
HTML:
<a download="content.txt" href={{ Download() }} target="_blank" >Download</a>
<button ng-click="Download()" >Alternatif</button>
有人有想法吗?
答案 0 :(得分:1)
对于您提供的两种用法,<button>
确实无法正常工作,因为&#34;点击&#34; event返回一个字符串,没有任何操作。
<a href="{{ Download() }}">
的问题在于它在生成组件时运行。因此,创建的Blob
的值很可能是空的。
在下面的代码中,我更改了逻辑以更新&#34; a&#34;单击它时的元素。其余的都保持不变。
App.controller('Forumlaire_Controller', function ($scope, Shared_Service) {
$scope.Download = function() {
var a = document.getElementById("downloadLink"),
url = Shared_Service.Service_download();
a.href = url;
a.target = "_blank";
a.download = "filename.txt";
}
})
.config( function($compileProvider) {
$compileProvider.aHrefSanitizationWhitelist(/^\s*(|blob|):/);
});
App.factory('Shared_Service', function($q) {
return {
Service_download: function() {
var url = $window.URL || $window.webkitURL;
var data = $('#copy_Output_logs').text();
console.log($('#copy_Output_logs').text()) // On ng-click the text showup correctly
console.log(url.createObjectURL(new Blob([data], { type: 'text/plain' }))); //Via ng-click the url generates correctly in the console.
return url.createObjectURL(new Blob([data], { type: 'text/plain' }));
}
}
});
至于HTML
<a href="#" id="downloadLink" ng-click="Download()">Download</a>