0

I have a function validateSesion that i need to call every time a controller is executed.

There is a way to trigger the function without putting the call to the function in all the controllers?

3
  • Please post what you tried? Commented Jul 28, 2016 at 16:10
  • are you sure that you want to call a function every time a controller is instantiated? it's common practice to have multiple controllers on a page, which could mean quite a few more calls to said function than expected... Commented Jul 28, 2016 at 16:15
  • It's probably more likely that you have a function you want to execute for each new page a user visits, which isn't the same as every time a controller is instantiated. this kind of task is typically done within whichever router you are using. Commented Jul 28, 2016 at 16:16

1 Answer 1

1

The way I would recommend accomplishing such a call would be to create event handlers for your route changes. This way every time you change your route or state (if you are using ui-router) you can run your code.

You would place this in your app's run function and attach the event handlers to the $rootScope as shown below:

    angular.module('app', [
    //Your Dependencies Here

    ]).run(init);

function init($rootScope, sessionService) {
    //ngRoute
    $rootScope.$on('$routeChangeStart', function (angularEvent, next, current) {
        sessionService.validateSession();
    });

    //ui-router
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        sessionService.validateSession();
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.