Using node module in angularjs?

后端 未结 1 1026
梦如初夏
梦如初夏 2021-01-13 06:58

What\'s the best practice for using external code, e.g. code found in node modules, in angular?

I\'d like to use this https://www.npmjs.com/package/positio

相关标签:
1条回答
  • 2021-01-13 07:34

    To do this, I would crack open the package and grab the .js out of it. This package is MIT license, so we can do whatever we want. If you navigate to /node_modules/positionsizingcalculator/ you'll find an index.js. Open that up and you'll see the moudle export, which takes a function that returns an object.

    You'll notice this is an extremely similar pattern to .factory, which also takes a function that returns an object (or constuctor, depending on your pattern). So I'd do the following

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

    and the inject 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 good for one off grabs of the JS, but if you want a more extensible solution, http://browserify.org/ is a better bet. It allows you to transform your requirements into a single package. Note that this could result in pulling down a lot more code that you might otherwise need, if you make one require bundle for your whole site, as this is not true AMD, and you need to to load everything you might want one the client, unless you make page specific bundles.

    You'd still want to do the require in a factory and return it, to keep it in angular's dependency injection framework.

    0 讨论(0)
提交回复
热议问题