Calling Factory from outside AngularJS

What 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'));

      

+3


source to share


2 answers


If you want to call your factory outside angular, you will need to get the injector from your module, that is:

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

      



You can usually use this when writing a unit test, but you should try to avoid it in production code.

Don't try to access your angular app from outside, otherwise typical use of factory / services etc. will be through the injection dependency while you are in the application.

+14


source


you can depend on a module and use it.



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

      

0


source







All Articles