3

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.

Ursin Brunner
  • 2,310
  • 1
  • 24
  • 24
  • 1
    I'd use 'value' rather than 'constant', but yeah, generally this is the best way unless you want extra functionality (angular-specific modifications), in which I'd put it into a service or factory. – casraf Dec 15 '15 at 17:24
  • [angular-moment](https://github.com/urish/angular-moment) – Maher Dec 15 '15 at 17:43
  • [angular-lodash](https://github.com/cabrel/angular-lodash) – Maher Dec 15 '15 at 17:46

1 Answers1

2

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.

FrailWords
  • 886
  • 7
  • 19