Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register a function on $rootScope on angularjs ready

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?

like image 569
poussma Avatar asked Mar 07 '13 11:03

poussma


1 Answers

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.

like image 140
Mark Rajcok Avatar answered Nov 15 '22 16:11

Mark Rajcok