Question

I'm trying to achieve a program structure like this:

enter image description here

The problem here is, when there is no apparent controller using the Features in the beginning, they are not instantiated and not registered in the FeatureRegistry, therefore they can't show up in the View. But what I would like is to achieve is that they show up in the view, then there template is loaded via ng-include and then in the template there are specific controllers for each feauture. These controllers are the ones that are using the Features.

The features are basically only there to tell about the location of templates and icons, which to use, and also to kick off the start of the Feature.

But back to my initial question:
How to instantiate the services even if they are not needed at the moment?

Or is there another function, that I can use for that instead of service? I would also like if you point me to that then :)

Was it helpful?

Solution

You can ask for it in the run part of your application, injector will invoke it.

angular.module("myApp", []).
    factory("EagerService", function () {
        console.log("I'm ready.");
    }).
    run(function (EagerService) {
        console.log("EagerService is ready.");
    });

Yet, as far as I understand, you have child/sub controllers that need this EagerService. Why don't you inject it there?

OTHER TIPS

(Since this is relatively old - this answer is for future readers - but I stumbled across this question so maybe someone else will too) If you use providers/config blocks - they are done eagerly, so it's better to do eager initialization code there. You are/were probably thinking in terms of services/run blocks.

To demonstrate with code, this alert will not pop (assuming myServiceModule is a module that your application depends on and myService is not injected anywhere):

angular.module('myServiceModule', []).service('myService', function () {
    alert("service");

    // service
    return {};
});

However this alert will pop even if no one is depending on the myProvider service:

angular.module('myProviderModule', []).provider('myProvider', function () {
    alert("provider");

    // Define your service here. Can be an array of inject-ables 
    // instead of a function.
    this.$get = function () {
        // service
        return {};
    };
});

You can see this in action in this plunker.

Read more about providers in the official documentation here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top