构建数据表,有2个主要功能
到目前为止,能够对表进行排序,并可以使用jQuery下载CSV。但是使用jQuery并不是Angular方式所以需要能够使用纯JS。
指令“exportToCsv”
angular.module('myApp')
.directive('exportToCsv', function(){
return {
restrict: 'A',
link: function (scope, element, attrs) {
var el = element[0];
element.bind('click', function(e){
var table = e.target.nextElementSibling;
var csvString = '';
for(var i=0; i<table.rows.length;i++){
var rowData = table.rows[i].cells;
for(var j=0; j<rowData.length;j++){
csvString = csvString + rowData[j].innerHTML + ",";
}
csvString = csvString.substring(0,csvString.length - 1);
csvString = csvString + "\n";
}
csvString = csvString.substring(0, csvString.length - 1);
// USING JQUERY ABLE TO DOWNLOAD THE CSV
var csvExport = $('<a/>', {
href:'data:application/octet-stream;base64,'+btoa(csvString),
download:'report.csv'
}).appendTo('body');
console.log('variable jqueryExport', csvExport);
csvExport[0].click();
csvExport.remove();
// UNABLE TO DOWNLOAD CSV USING ANGULAR ONLY
var csvExport = ('<a/>',{
href:'data:application/octet-stream;base64,'+btoa(csvString),
download:'report.csv'
});
// Seems like all the answers want to append to HTML rather than it's own node
element.append('csvExport');
}
};
});
HTML
...
<button export-to-csv>Download</button>
<table>...</table>
...
如何将csvExport
附加到其元素,下载,然后将其删除?
答案 0 :(得分:0)
我可能会使用动态ng-href将自己设置为csv的值。
类似的东西:
<table id="data-to-download">...</table>
<a ng-href="{{ dataUri('#data-to-download') }}" download="report.csv">Download</a>
然后使用传入的选择器('#data-to-download')实现像上面一样的dataUri。
答案 1 :(得分:0)
能够将下载链接附加到指令元素。
Angular Way
var determineWinner: Int? {
guard let chosen = chosen, let rval = rval else {
//handle error, either chosen or rval is nil
return nil
}
switch ((chosen, rval)) {
case let (x, y) where x == y: return 2
case (1, 3): return 1
case (1, 2): return 0
case (2, 1): return 1
default:
print("handle default case here")
return nil;
}
}