Don P
Don P

Reputation: 63667

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?

Upvotes: 1

Views: 3154

Answers (2)

Vishnu Vivek
Vishnu Vivek

Reputation: 2121

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

Upvotes: 1

Nikhil Dev
Nikhil Dev

Reputation: 126

I would prefer moving that function into the resolve section of your $stateProvider. Your state config could look something like

.config(['$stateProvider', function($stateProvider) {

  $stateProvider
  .state('myRoute', {
    url: '/myUrl',
    templateUrl: '/template.html',
    controller: 'MyController',
    controllerAs: 'vm',
    resolve: {
      dummyVariable: function(MyService, $stateParams) {

        MyService.functionToBeCalled();

        return true;
      }
    }
  });

Upvotes: 0

Related Questions