I am creating an angular provider (because it needs to be configurable) and I need it to initialize once when the app starts so I have an init() function inside the $get function of my provider which is not returned as part of the public. The init() function also attaches a resize event to the window. Here is a very simplified version...
angular.module('my.services').provider('breakpoints', function(){
var breakpoints = [];
var currentBreakpoint = {};
init();
return({
$get: instantiate
});
function instantiate($rootScope, $window) {
_initService();
// Public API
return({
current: current,
});
function current() {
return currentBreakpoint;
}
function _windowWidthChanged(){
// Check if breakpoint has changed and broadcast event if it has
}
function _initService(){
angular.element($window).bind('resize', _windowWidthChanged);
_windowWidthChanged();
}
}
});
My question is, when does this initService() function run?
I know it isn't run if I don't inject it into any controllers/directives etc, even though it is part of a module that is injected into my app. I know this because I put a console.log() into the function.
If I inject the service into a directive that needs it I know the function runs when the page loads, which is what I want, but will it run every time it is injected into a different directive? If so then I would get multiple events attached to the window and it would $broadcast multiple events when the breakpoint changes, which in turn would trigger all my directives to re-layout, which would be a nightmare.
Basically I want the service to initialize once when it is first used. Attach a single resize event to the window and broadcast a single event if the breakpoint changes.
Your service will be instantiated once when it is injected for the first time.
From Angular documentation on providers:
All services in Angular are singletons. That means that the injector uses each recipe at most once to create the object. The injector then caches the reference for all future needs.
The actual order of instantiation depends on the dependencies among different scopes. Angular sorts dependencies so required dependencies are instantiated before the code that uses them. Incidentally, this is how Angular detects cycles in provider dependencies.