Blake
Blake

Reputation: 2397

How do you use underscore js mixins within an angular module

I have a few different angular modules that will share the same method. These modules don't really lend themselves to inheritance, but I want to remain DRY. Thus I wanted to use the mix-in pattern. In the project I'm working on, we are also using underscore js. I'm trying to instantiate an angular module for my mixin as follows:

angular.module('my.module', [])
  .factory('myMixinFunction', function () {
    _.mixin({
      myMixinFunction: function (param) {
        // do something
        return;
      }
    });
  });

Now my question is, how do I load this mixin into another module? I'm thinking it would look something like this -

angular.module('some.other.module', ['my.module'])
  .factory('myOtherModule', function (myMixinFunction) {
      /// Other module code
  });

I know I'll have to list the mixin module as a dependency, but where do I actually perform the extension? Ideally, I would like my mixin to be able to access the elements within 'myOtherModule'. Anyone have any advice on this? Is there an 'angular way' to accomplish this?

Upvotes: 0

Views: 597

Answers (1)

Dexygen
Dexygen

Reputation: 12561

Instead of using underscore's _.mixin() functionality, you might want to instead define myMixinFunction as a service. See: What is the difference between module.factory and module.service and how might both be applied?, noting services/usage: "Usage: Could be useful for sharing utility functions"

Upvotes: 1

Related Questions