我得到帮助在客户端将 json 保存为文件 here .在这个 fiddle 中,代码非常短。
var a = document.createElement('a');
a.download = "backup.json";
a.href = url;
a.textContent = "Download backup.json";
document.getElementById('content').appendChild(a);
我试图创建一个 angularjs 指令,以便它调用范围内的方法来获取数据。沿着这条线。
module.directive('myDownload', function ($compile) {
return {
restrict:'E',
scope:{ getData:'&getData'},
link:function (scope, elm, attrs) {
elm.append($compile(
'<a class="btn" download="backup.json"' +
'href=' + scope.getData() + '>' +
'Download' +
'</a>'
)(scope));
}
};
});
这行不通。如何制作 linked fiddle进入指令?
最佳答案
这样的事情怎么样:Fiddle
指令代码如下:
module.directive('myDownload', function ($compile) {
return {
restrict:'E',
scope:{ getUrlData:'&getData'},
link:function (scope, elm, attrs) {
var url = URL.createObjectURL(scope.getUrlData());
elm.append($compile(
'<a class="btn" download="backup.json"' +
'href="' + url + '">' +
'Download' +
'</a>'
)(scope));
}
};
});
Controller :
module.controller('MyCtrl', function ($scope){
var data = {a:1, b:2, c:3};
var json = JSON.stringify(data);
$scope.getBlob = function(){
return new Blob([json], {type: "application/json"});
}
});
关于javascript - 创建[下载]按钮的指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16342659/