view raw
Donny P Donny P - 6 months ago 35
AngularJS Question

Run a function every time an Angular controller is loaded

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:

function(event, toState, toParams, fromState, fromParams){

Is there a better alternative?


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

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 

Edit: For your specific need, the code for Google Analytics can be handled efficiently in Angular $http Interceptor. Refer Angular $http Interceptors