]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/services/file.js
83e0d295d81dcc4a95309e41b0b1e3fad21cdf2d
[Evergreen.git] / Open-ILS / web / js / ui / default / staff / services / file.js
1 /**
2  * File upload reader.
3  * http://stackoverflow.com/questions/17063000/ng-model-for-input-type-file
4  *
5  * After reading, the contents will be available in the scope variable
6  * referred to by container="..."
7  */
8
9 angular.module('egCoreMod')
10 .directive("egFileReader", [function () {
11     return {
12         scope: {
13             container: "="
14         },
15         link: function (scope, element, attributes) {
16             // TODO: support DataURL, etc. via attrs
17             element.bind("change", function (changeEvent) {
18                 var reader = new FileReader();
19                 reader.onload = function (loadEvent) {
20                     scope.$apply(function () {
21                         scope.container = loadEvent.target.result;
22                     });
23                 }
24                 reader.readAsText(changeEvent.target.files[0]);
25             });
26         }
27     }
28 }])
29
30 .directive('egJsonExporter', ['FileSaver', 'Blob', function(FileSaver, Blob) {
31     return {
32         scope: {
33             container: '=',
34             generator: '=',
35             defaultFileName: '='
36         },
37         link: function (scope, element, attributes) {
38             element.bind('click', function (clickEvent) {
39                 if (scope.generator) {
40                     scope.generator().then(function(value) {
41                         var data = new Blob([JSON.stringify(value)], {type : 'application/json'});
42                         FileSaver.saveAs(data, scope.defaultFileName);
43                     });
44                 } else {
45                     var data = new Blob([JSON.stringify(scope.container)], {type : 'application/json'});
46                     FileSaver.saveAs(data, scope.defaultFileName);
47                 }
48             });
49         }
50     }
51 }])
52 ;