0

I am trying to inject a few helpers (lodash and a few of my own) in Angular controllers so I have:

angular.module('app').factory("_", Lodash);
Lodash.$inject = ['$window'];
function Lodash($window) {
  if ($window._) 
    return $window._;
}

angular.module('app').factory("_", Helper);
Helper.$inject = ['$window']; 
function Helper($window) {  
  return {
    test: function () {
      return "test";
    }
  }
}

So I would like all helpers to be accessible under _ and I would define them in a few JS files ... Can this be done?

With my code only one of them work: lodash methods or test().

2
  • beacuse both of your factories have the same name.. Commented Apr 17, 2016 at 19:42
  • yes, I know ... my question is if I can merge the methods in lodash and my own in the same factory accessible in _ Commented Apr 17, 2016 at 19:43

2 Answers 2

1

For services that don't require dependencies ($window isn't crucial here because it serves for no purpose and can be replaced with window or _ global) config block is a good place to define them, because constant services are already available there.

app.config(function ($injector, $provide) {
  var lodash = $injector.has('_') ? $injector.get('_') : {};
  angular.extend(lodash, window._);
  $provide.constant('_', lodash);
});

app.config(function ($injector, $provide) {
  var lodash = $injector.has('_') ? $injector.get('_') : {};
  angular.extend(lodash, {
    test: ...
  });
  $provide.constant('_', lodash);
});

When the service is defined this way, its value can be extended several times, the order of config blocks doesn't matter.

Alternatively, service value can be changed with decorator, in order to do that the service should be already defined.

Sign up to request clarification or add additional context in comments.

Comments

0

You can not redeclare a factory. As you already noticed, this will overwrite the previous.

You could prepare the helper in separate files and register them in one factory call elsewhere in your app.

1 Comment

Yes, that is my idea ... To merge lodash methods with my own methods under _ factory. But how can I do that? Could you give an example with the code I posted?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.