Using node module in angular?

What's the best practice for using external code eg. code found in node modules in angular?

I would like to use this https://www.npmjs.com/package/positionsizingcalculator node module in my angular app. I have created an angular service designed to wrap a node module and now I want the service to use the node module.

'use strict';

angular.module('angularcalculator')
  .service('MyService', function () {
    this.calculate = function () {
      return {
        //I want to call the node module here, whats the best practice?
      };
    }
  });

      

+3


source to share


1 answer


To do this, I hacked the package and pulled the .js out of it. This package is MIT licensed, so we can do whatever we want. If you go to /node_modules/positionsizingcalculator/

, you will find index.js

. Open this up and you will see a moudle export that takes a function that returns an object.

You will notice that this is a very similar template for .factory

, which also accepts a function that returns an object (or constuctor, depending on your template). So I would do the following

.factory('positionsizingcalculator', function(){
        basicValidate = function (argument) {
        ... //Insert whole declaration in here
        return position;
}) 

      

and put it where you need it:



.controller('AppController', function(positionsizingcalculator){
    //use it here as you would in node after you inject it via require.
})

      

- Edit: This is fine for one JS capture, but if you want a more extensible solution, http://browserify.org/ is the best bet. This allows you to transform your requirements into a single package. Please note that this can result in much more code being allocated that you might need if you make one package for your entire site as it is not AMD and you need to download whatever you might need if you don’t make bundles of pages.

You will still want to execute the request in factory

and return it to keep it in angular's dependency injection framework.

+5


source







All Articles