18

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?

poussma
  • 7,033
  • 3
  • 43
  • 68
  • 4
    Why cant you do this in a service and inject that service everywhere you have delete button and call the required function on that service? – ganaraj Mar 07 '13 at 11:25
  • 1
    Because you did not told me before :) ! thx, I moved that in a service and I can get it everywhere I need and it works fine! – poussma Mar 07 '13 at 11:36

1 Answers1

43

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.

Peter
  • 573
  • 3
  • 12
Mark Rajcok
  • 362,217
  • 114
  • 495
  • 492
  • 11
    +1 This is the correct answer to the question asked... even if the *real* answer was "don't do it that way". ;) haha. – Ben Lesh Mar 07 '13 at 20:20