Kohjah Breese
Kohjah Breese

Reputation: 4136

Inject Factory into Factory

How do you make a factory available from another factory? Using the below the console tells me there is an error (injector:unpr).

angular.module( 'fb.services', [] ).factory( 'getQueryString', function() {
    return { call: function( qs ) {
        var result = {}, queryString = qs.substring( 1 ), re = /([^&=]+)=([^&]*)/g, m;
        while ( m = re.exec( queryString ) )
            result[decodeURIComponent( m[1] )] = decodeURIComponent( m[2] );
        return result;
    }}
});

angular.module( 'fb.services', ['fb.services'] ).factory( 'getReferrer', function( getQueryString ) {
        var qry = getQueryString.call( 'query=string&this=that' );
        // fails to find getQueryString
});

Upvotes: 1

Views: 6274

Answers (1)

PSL
PSL

Reputation: 123739

You just need to do:

angular.module( 'fb.services').factory( 'getReferrer',['getQueryString', function( getQueryString ) {
        var qry = getQueryString.call( 'query=string&this=that' );
        // fails to find getQueryString
}]);

When you use the second argument in the module declaration angular.module( 'fb.services','fb.services'] ) it means you are redefining/defining the module again with new dependencies, which means anything registered previously are lost.

After you have defined your module, you just access it by doing angular.module( 'fb.services') (omit second argument, so it becomes a getter of the module that has been already defined)

Also see Dependency Injection and annotate

Upvotes: 5

Related Questions