jQuery 如何在 angularjs 上的 $rootScope 上注册一个函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15269803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to register a function on $rootScope on angularjs ready
提问by poussma
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.
我需要在 angularjs 中注册一个随处可用的方法。此方法有 2 个参数(资源 id,删除成功回调),它使用资源提供程序来实际删除项目。
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:
然后要注册它,我需要 angularjs 向我注入$rootScope
and MyResourceProvider
。我的第一个想法是在我的主页控制器中这样做:
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)...
这里开始实际上是我的问题。这在常规导航(主页 -> 列表 -> 选择 -> 删除)中工作正常,但如果用户直接访问删除按钮可用而无需通过主页的页面,则此方法将不可用(因为HomeController 尚未初始化)...
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...
我试过了,myApp.config()
但没有成功...
Any idea?
任何的想法?
回答by Mark Rajcok
As @ganaraj mentioned in the comments, a service is probably a better choice for this.
正如@ganaraj 在评论中提到的那样,服务可能是更好的选择。
However, to answer your question, you can use the run()method.
但是,要回答您的问题,您可以使用run()方法。
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.
run() 在所有模块加载后调用。