Kohjah Breese
Kohjah Breese

Reputation: 4136

Calling a Factory From Outside of AngularJS

How do you call a factory? As defined below.

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

Upvotes: 4

Views: 4862

Answers (2)

PSL
PSL

Reputation: 123739

If you want to call your factory outside of the angular you would need to get an injector from your module. i.e:

angular.injector(['fb.services']).get('getQueryString').call();

You can typically use this while writing unit test, but you should try to avoid doing this in production code.

Try not to access angular app outside, Otherwise typical usage of the factory/services etc would be through dependency injection while you are in the app.

Upvotes: 15

hsinglin
hsinglin

Reputation: 11

you can dependency the module and use it.

angular.module('fb.controller', ['fb.services'])
  .controller('fb.controller',['getQueryString',function(getQueryString){
     alert(getQueryString.call('this=that&me=you'));
 }])

Upvotes: 0

Related Questions