Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "eager load" a service in AngularJS? (instantiate it before its needed, automatically)

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 :)

like image 987
JustGoscha Avatar asked Mar 21 '13 15:03

JustGoscha


1 Answers

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?

like image 92
Umur Kontacı Avatar answered Sep 19 '22 13:09

Umur Kontacı