1

I'm trying to include typical javascript library(JSZip) in to my angularjs application.

At first i have added included JSZip library in to my application and then added script reference to my index page.

Next i have created a simple object of JSZip in one of my module and trying to create zip. but all of sudden, i am getting compilation error in typescript while building my application in VS2015(visual studio), saying that "Cannot find name JSZip".

How to load non angular dependency in angular application. i have spent a complete day. i didn't find any clue.

i have tried multiple ways to get the dependency dynamically and also tried oclazyload to load JSZip dependency ..but not helps.

            var zip = new JSZip(); <=== this is where the problem is..
            zip.file("File1", atob(response.Data));
            zip.file("File2", atob(response.Data));
            zip.generateAsync({ type: "blob" })
                .then(function (content) {
                    // saveAs is from FileSaver.js
                    saveAs(content, "example.zip");
                });
Kranthi Kumar
  • 101
  • 1
  • 9

1 Answers1

2

Inject non-angular JS libraries

Include the JS file into your HTML file

<script src="http://stuk.github.io/jszip/dist/jszip.js"></script>

In your module angular add constant 'jszip' for exemple

var app = angular.module('myApp', [])
  .constant('jszip', window.JSZip)
  .run(function($rootScope) {
    $rootScope.JSZip = window.JSZip;
})

Inject 'jszip' in your controller, and you will solve your problem

app.controller('myCtrl', function($scope, 'jszip') {
  var zip = new jszip();
  ...
});

For the downloading part (saveAs function), include FileSaver.js into your HTML file

<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.js"></script>

In your controller for exemple

$scope.exportZip = function(){
    var zip = new JSZip();
    zip.file("Hello.txt", "Hello World\n");

    zip.generateAsync({type:"blob"})
    .then(function(content) {
      saveAs(content, "example.zip");
    });
};
Nevada
  • 143
  • 1
  • 10