Search code examples
angularjsangularjs-routingangularjs-rootscope

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:

$rootScope.$on('$stateChangeSuccess', 
  function(event, toState, toParams, fromState, fromParams){
    myFunction();
  }
);

Is there a better alternative?


Solution

  • 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 
    }
    

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