9

I got help to save json as file in client side here. Code is very short as in this fiddle.

var a = document.createElement('a');
a.download    = "backup.json";
a.href        = url;
a.textContent = "Download backup.json";

document.getElementById('content').appendChild(a);

I was trying to create an angularjs directive so that it calls a method in scope to get the data. Along this line.

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

This doesn't work. How can make the linked fiddle into a directive?

4

2 回答 2

14

How about something like this: Fiddle

Here's the directive code:

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"});
  }
});
于 2013-05-02T16:58:14.200 回答
2

我最终来到这里试图解决类似的问题。在我的 Angular 页面中,我有一个通过 Ajax 检索到的 JSON,它呈现为 HTML,但我希望可以通过链接下载“原始”JSON。

OP 和投票最多的方法的问题是 HTML DOM 在您的控制器中进行操作,这违背了使用 MVVM 的目的。我认为您这样做的原因是因为 Angular 阻止了为 blob 创建链接(通过在生成的 blob URL 前添加“不安全:”)。

幸运的是,Angular 提供了一种应用白名单某些 URL 前缀的方法, 因此当您使用它时不会被阻止URL.createObjectURL()......在这种情况下,我们包括blob

这是我对在JSFiddle上运行的看法

于 2014-10-22T18:45:41.120 回答