Gp17 Gp17 - 4 months ago 31
Javascript Question

how to call a function before every $state.go() in angular using stateProvider

The title says it all, but in more details; I want to check if the user is authenticated by checking if cookie is available or not before very

$state.go()
call, is it possible to set it globally and not being forced to do it on every
state.go()
function ?

Answer

So you can hook into the $stateChangeStart event which happens each time a transition is about to start. Docs

You would do something like this:

app.run(['$state', '$rootScope', function ($state, $rootScope) {
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        // calling event.preventDefault() will prevent the transition, so this is used
        // when you want to stop certain transitions.
    }
});

Now there are two options for changing whether you want to prevent a route.

You can use the toState and fromState to look up in a routing dictionary.

You can use a service or factory to change whether you can or not.

So if you create a factory, this is an example, it gives you the concept:

app.factory('routingLogic', function () {
   var singletonShouldRoute = true;
   var service = {
       canRoute: canRoute,
       setCanRoute: setCanRoute
   };
   return service;

   function setCanRoute(shouldRoute) {
      singletonShouldRoute = shoudldRoute
   }

   function canRoute() {
      return singletonShouldRoute ;
   }
}

app.controller('somePage', ['routingLogic', '$state', function (routingLogic, $state) {
    var vm = this;

    vm.shouldRoute = false;

    vm.changeShouldRoute = function () {
        routingLogic.setCanRoute(vm.shouldRoute);
    } 

    vm.goNextPage = function () {
        $state.go('some page');
    }
});

app.run(['$state', '$rootScope', 'routingLogic', function ($state, $rootScope, routingLogic) {
    $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
        // calling event.preventDefault() will prevent the transition, so this is used
        // when you want to stop certain transitions.

        if (!routingLogic.canRoute()) { event.preventDefault(); }
    }
});