Inject non-angular JS libraries

2019-05-10 14:14发布

问题:

In our project we use NPM together with Browserify for third-party dependency management, which works great in combination with AngularJS (thanks to the CommonJS-modules).

The following code shows the dependency-structure, which works great with angular's dependency injection:

(function () {
    'use strict';

    var moment = require('moment');
    var lodash = require('lodash');

    var angular = require('angular');

    var app = angular.module('myProject', [
        require('angular-ui-router'),
        require('angular-animate'),
        require('angular-resource'),
        require('angular-ui-bootstrap'),
        require('ng-file-upload'),
        require('angular-smart-table'),
    ]);

    app.constant('moment',moment);
    app.constant('lodash',lodash);

})();

My question is about plain-javascript-libraries like moment or lodash. Whats the best way to inject them into my controllers and directive? Is the app.constant()-approach the way to go or are there any drawbacks I don't consider?

I realize there are a lot of "angular-mapper" projects for this libraries around, but I don't expect them to get supported long enough and would therefore rather stick to the original-libraries.

回答1:

The comments to your question do point in the right direction - look for angular'ized forms of those libraries first. If not, then you could do something like -

var lodash = angular.module('lodash', []);
lodash.factory('_', function() {
  return window._;
});

and then use this module dependency and inject '_' in you controllers and services.

Even if you use app.constant, it can still be 'injected' as a dependency. The 'factory' way gives you a bit more flexibility I guess.