Initialize Angular Service (factory) when application start

Grigorii picture Grigorii · May 29, 2015 · Viewed 10.1k times · Source

In my Angular application I adding tracing functionality, which should work as separate plugin, so if script included into HTML Angular should create service and initialize (run) it. Plugin is service because it has mandatory dependency on $rootScope. For implementation I select to use Angular factory, like (code is in myservice.js):

angular.module('app').factory('mysevice', ['$rootScope', '$interval', serviceFunc]);

function serviceFunc($rootScope, $interval) {

    return {
        run: function () { ... } 
    }
}

And now I have problem how to immediately initialize it. My solution is to enhance Angular app run function (code is in myservice.js):

window.app.run(['mysevice', function (srvc) {
        srvc.run();
    }]);

Where app defined in separate main app.js file like:

var app = window.app = angular.module('app', [...]);
app.run(['$state', 'breeze', ...,
function ($state,  breeze, ...) { ..real initialization..  }

The code is working fine. Both main run and run for myservice calls are fine. The application together with the service are working well, but the code looks ugly, especially storing the app in the global window object and multicasting the run function.

Is there a better way to do Angular service and initialize it immediately after app starts with some other Angular services dependencies.

Answer

Wédney Yuri picture Wédney Yuri · May 29, 2015

You can call angular.module('app').run(function(){...}). So you will not need a global variable anymore.

Example:

angular.module('app').run(['mysevice', srvc.run.bind(srvc)]);