Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - creating factory during run time

Tags:

angularjs

I am using odata service and i want to create helper service per each entity type, so after getting the metadata i am creating the factory (this is done before angular was bootsrapped)

  var serviceName = allTypes[type].shortName + 'RepositoryService';
                angular.module('app').factory(serviceName, [function() {

                    function sayHello() {
                        console.log('hello');
                    }

                    return {
                        sayHello: sayHello
                    };
                }]);

and I am trying to consume it in another controller

 sensorService = $injector.get('CSensorRepositoryService');

and i am getting an error

Error: [$injector:unpr] Unknown provider: CSensorRepositoryServiceProvider <- CSensorRepositoryService

when iterated over all the available factories I saw that this factory exits

var mod = angular.module('app');
        for (var id in mod._invokeQueue) {
            if ((mod._invokeQueue[id])[1] === 'factory') {
                console.log( id + " " + ((mod._invokeQueue[id])[2])[0]);
            }
        }

and when I tried to take factory which was "hard coded" all was ok what I am doing wrong?

like image 987
li-raz Avatar asked Aug 15 '26 02:08

li-raz


1 Answers

You can do this by exposing the providers from app.config so...

var app = angular.module('app',[]);
app.config(function($provide){
    app.register =
        {
            factory: $provide.factory,
            service: $provide.service,
            constant: $provide.constant
        };
});

Then at a later time...

app.register.factory('myFactory',function(){...});

I'd just be sure this doesn't happen someplace where it could occur repeatedly

This is the same concept as presented here.

like image 95
calebboyd Avatar answered Aug 16 '26 22:08

calebboyd