How to register a function on $rootScope on angularjs ready

Problem

I need to register a method available everywhere in angularjs. This method has 2 arguments (the resource id, the callback on deletion success) and it uses the resource provider to actually delete the item.

Then to register it, I need that angularjs injects me the $rootScope and MyResourceProvider. My first idea was to do that in my home page controller:

var HomeCtrl = function ($rootScope, MyResourceProvider) {
$rootScope.confirmAndDeletePackage = function (sId, fCallback) {
// do some stuff
MyResourceProvider.delete({id: sId}, fCallback);
}
}

Here starts actually my issue. That works fine in a regular navigation (home -> list -> select -> delete) but if the user accesses directly a page where the delete button is available w/o passing through the home page, this method will not be available (because the HomeController has not been initialized)…

So, my question is where can I move this piece of code to ensure it will always be executed at the application bootstrap.

I tried on myApp.config() but w/o success...

Any idea?

Problem courtesy of: poussma

Solution

As @ganaraj mentioned in the comments, a service is probably a better choice for this.

However, to answer your question, you can use the run() method.

myApp.run(function($rootScope, MyResourceProvider) {
$rootScope.confirmAndDeletePackage = function (sId, fCallback) {
// do some stuff
MyResourceProvider.delete({id: sId}, fCallback);
}
})

run() is called after all modules have been loaded.

Solution courtesy of: Mark Rajcok

View additional discussion.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.