Not able to call factory method after including factory function with $provide.factory in angular.js

242 Views Asked by At
app.config(['$controllerProvider','$compileProvider', '$filterProvider', '$provide',function($controllerProvider,
        $compileProvider, $filterProvider, $provide) {
        app.register = {
          controller: $controllerProvider.register,
          directive: $compileProvider.directive,
          filter: $filterProvider.register,
          factory: $provide.factory,
          service: $provide.service
        };
      }
]);

app.controller('myCntrl', ['$scope', function($s) {
   app.register.factory('customFactory',[customFactory]);
   customFactory.init();
 });

factory.js

function customFactory(){
    var c= {};
    c.init = function(){
        console.log('init function');
    }
    return c;
}

Here I will be adding factory.js file in runtime and I now need to inject custom factory in my controller. So I have used $provide.factory method for it. But, I am not able to call init() function inside customFactory

1

There are 1 best solutions below

0
miqh On

Inside the controller that dynamically registers customFactory, the customFactory name binding is just a function. To call init() at the location you've noted, you'll need to invoke customFactory as a function.

customFactory().init();

However, if you've got another recipe elsewhere (e.g. controller) which needs to depend on customFactory, then you can access init() as you might expect.

app.controller('anotherCtrl', ['customFactory', function (customFactory) {
    customFactory.init();  // OK!
}]);

When customFactory gets registered, the AngularJS dependency injector knows how to create it as a singleton and subsequently you can just access it as a value.