如何在角度模块中使用下划线js mixins

时间:2014-02-11 14:52:07

标签: javascript angularjs underscore.js

我有几个不同的角度模块,它们将共享相同的方法。这些模块并不能真正用于继承,但我想保持DRY。因此我想使用混合模式。在我正在研究的项目中,我们也使用下划线js。我正在尝试为我的mixin实例化一个角度模块,如下所示:

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

现在我的问题是,如何将这个mixin加载到另一个模块中?我认为它看起来像这样 -

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

我知道我必须将mixin模块列为依赖项,但我在哪里实际执行扩展?理想情况下,我希望我的mixin能够访问'myOtherModule'中的元素。有人对此有任何建议吗?是否有一种“有角度的方式”来实现这一目标?

1 个答案:

答案 0 :(得分:1)

您可能希望将_.mixin()定义为服务,而不是使用下划线的myMixinFunction功能。请参阅:What is the difference between module.factory and module.service and how might both be applied?,注意服务/用法:“用法:可用于共享实用程序功能”