指令创建一个[下载]按钮 [英] Directive to create a[download] button

查看:97
本文介绍了指令创建一个[下载]按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有帮助JSON保存在客户端<文件href=\"http://stackoverflow.com/questions/16329293/save-json-string-to-client-pc-using-html5-api\">here. code是非常短,在这个小提琴。

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

我是想,使其调用范围的方法来获取数据来创建一个angularjs指令。沿着这条线。

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?

推荐答案

如何像这样:小提琴

下面的指令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));
     }
  };
});

控制器:

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

这篇关于指令创建一个[下载]按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆