Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - Inject Factory into the run of the main module

Tags:

angularjs

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?

like image 956
Kousha Avatar asked Dec 15 '22 20:12

Kousha


1 Answers

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/

like image 66
ivarni Avatar answered Jan 18 '23 13:01

ivarni