Kousha
Kousha

Reputation: 36189

AngularJS - Inject Factory into the run of the main module

I have a factory defined as app.factory('MyFactor'), and I want to inject this into the .run() of my main module.

I tried the same way I inject dependencies into a directive:

app.run(['MyFactory', function(MyFactory)
{

}]);

But I get an error say that this is an unknown Provider. What's wrong?

Upvotes: 4

Views: 9193

Answers (1)

ivarni
ivarni

Reputation: 17878

Injecting instances into a run function works. There were two wrong answers to this question claiming it doesn't.

Consider this:

angular.module('app',[])
.factory('myFactory', function() {
    return {
        foo: function() { return 'bar' }
    };
})
.run(['myFactory', function(myFactory) {
    alert(myFactory.foo());
}]);

It runs without errors and alerts the result from invoking a function on the myFactory service (yes it's still a service even if you call it a factory).

Most likely your error is caused by a misspelling of the name. In your posted code you have app.factory('MyFactor') which is missing a trailing "y".

JSFIDDLE: http://jsfiddle.net/os4erzjx/

Upvotes: 12

Related Questions