2

Liked the nice CSV parser & unparser of PapaParse. Can any one help me to get this combine with Angular JS.

I like to make PapaParse work in Angular Way. Trying for a solution.

Felix
  • 245
  • 2
  • 10

4 Answers4

7

I actually didn't do anything fancy to load it. Just add it to html file and to my lib folder. In my case: /lib/papaparse.min.js

and to index.html. As usual script:

<script src="lib/papaparse.min.js"></script>

then I just used it in my Controller:

Papa.parse(data, {
    complete: function(results) {
        console.log("Finished:", results.data);
    }
});
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
  • 2
    This approach works fine unless you need to stub or mock PapaParse out for unit testing of your controller. You don't want to get into a situation where you are monkey patching in your test setup. – Martin Aug 08 '16 at 22:53
4

You can use value to provide self contained third party libraries.

angular.module('your.app')
    .value('yourLib', yourLib);

Then in your controller, or service, you would bring it in the normal way using DI

angular.module('your.app')
    .controller('YourController', YourController);

YourController.$inject = ['yourLib'];
function YourController(yourLib) {

   //. . .  
} 

If the third party line is a constructor function, requires it be newed, you may want to create a factory or a provider that has a method that accepts the passes params to the constructor returns a new instance.

Edit

After looking at PapaParse, you would want to register it with the angular injector using value.

Martin
  • 15,820
  • 4
  • 47
  • 56
  • agree with you. Will be helpfull with a example (a fiddle) – Felix Dec 30 '14 at 11:42
  • @felix, unfortunately Papaparse isn't hosted anywhere with the correct MIME type -- Stackoverflow, Plunkr and Jsfiddle require the libs have the correct MIME. – Martin Dec 30 '14 at 11:57
  • noprops, I got a similar example with another library in SO http://stackoverflow.com/questions/14968297/use-underscore-inside-angular-controllers – Felix Dec 30 '14 at 12:19
  • 1
    @Felix, yes this approach is the same. The only difference is he is using a factory rather than a value. Value is a lighter approach, but both do the same thing. – Martin Dec 30 '14 at 12:24
  • it's now hosted on the following cdn: https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.js – Fergus Aug 08 '16 at 20:41
0

just use a front-end modularization tool like requirejs to load papaParser in the context and call the api in any of your controller or service.

hjl
  • 2,794
  • 3
  • 18
  • 26
  • I had completed my application, just for csv import, i had already need PapaParse so i don't like a new tool to be added. anyway Thanks. – Felix Dec 30 '14 at 07:35
0

Just inject the script url in your index.html & then in your controller, access it as - var Papa = window.Papa;. That's it! You are ready for further actions!

Tushar Walzade
  • 3,737
  • 4
  • 33
  • 56