每次加载 Angular 控制器时运行一个函数 [英] Run a function every time an Angular controller is loaded
问题描述
我想在每次加载任何 Angular 控制器时运行一个函数.
I want to run a function every time any Angular controller is loaded.
我发现的最好方法是将此处理程序附加到我网站上加载的第一个控制器中:
The best way I have found is to attach this handler in the first controller loaded on my site:
$rootScope.$on('$stateChangeSuccess',
function(event, toState, toParams, fromState, fromParams){
myFunction();
}
);
有更好的选择吗?
推荐答案
如果你只想在每次加载控制器时执行一个函数,下面就足够了.
If you just want to execute a function every time the controller is loaded, the following would suffice.
var init=function(){
//your code goes here
}
init();
但在大多数情况下,您需要仅在加载特定页面(路由)时执行功能.在这种情况下,请使用以下内容.
But in most cases, you would require a function to be executed only on load of a specific page (route). In this case, use the following.
if ($location.url() == "/your/page/url")
{
//Your function code or function call goes here
}
对于您的特定需求,可以在 Angular $http Interceptor 中有效处理 Google Analytics 的代码.参考 Angular $http 拦截器
For your specific need, the code for Google Analytics can be handled efficiently in Angular $http Interceptor. Refer Angular $http Interceptors
这篇关于每次加载 Angular 控制器时运行一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!