AngularJS HTML5 Download Directive (full jQuery version)
directive to create client side downloads
HTML
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script>
<div ng:init="filedata = 'Your file content'; name = 'your_file.txt'">
Filename:<br />
<input type="text" ng:model='name'/>
<br />
File content:<br />
<textarea ng:model="filedata"></textarea>
<br>
<a ng:download='filedata' filename="name" draggable>Download or drag to desktop</a>
</div>
JavaScript
var DownloadDirective, app, buildDirectiveFactory,
bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
slice = [].slice;
DownloadDirective = (function() {
DownloadDirective.$inject = ['$window'];
function DownloadDirective(window) {
this.setupDownload = bind(this.setupDownload, this);
this.link = bind(this.link, this);
var jQuery;
this.URL = window.webkitURL || window.URL;
this.Blob = window.Blob;
jQuery = angular.element;
jQuery.event.props.push('dataTransfer');
}
DownloadDirective.prototype.restrict = 'A';
DownloadDirective.prototype.link = function(scope, element, attrs) {
var download, draggable, filename, mimeType, updateDom;
download = attrs.ngDownload;
filename = attrs.filename;
mimeType = attrs.mimeType;
draggable = element.prop('draggable');
if (draggable) {
element.bind("dragstart", function(event) {
return event.dataTransfer.setData("DownloadURL", element.data('downloadurl'));
});
}
element.attr('href', '#');
element.click(function() {
if (element.attr('href') === '#') {
return false;
}
});
updateDom = (function(_this) {
return function() {
return _this.setupDownload(element, scope.$eval(download), scope.$eval(filename), scope.$eval(mimeType));
};
})(this);
scope.$watch(download, updateDom);
if (filename != null) {
scope.$watch(filename, updateDom);
}
if (mimeType != null) {
return scope.$watch(mimeType, updateDom);
}
};
DownloadDirective.prototype.setupDownload = function(a, data, filename, mimeType) {
var blob, objUrl;
if (filename == null) {
filename = 'file';
}
if (mimeType == null) {
mimeType = 'text/plain';
}
if (a.attr('href') !== '#') {
this.URL.revokeObjectURL(a.attr('href'));
}
blob = new this.Blob([data], {
type: mimeType
});
objUrl =...