Doge Doge - 2 months ago 17
AngularJS Question

AngularJS controller middleware

I have an Angular endpoint like so:

$stateProvider.state("auth.signin", {
url: "/signin",
views: {
"auth-view@auth": {
templateUrl: "views/auth/signin.html",
controller: "SigninController"
}
}
});


I want a before filter (or a middleware) for my
SigninController
so if the user is already logged in, I want to redirect him to my
HomeController
.

In pseudo code, I'm looking for something like this:

$stateProvider.state("auth.signin", {
url: "/signin",
views: {
"auth-view@auth": {
templateUrl: "views/auth/signin.html",
controller: "SigninController"
}
},
before: () => {
if (User.loggedIn() === true) {
return $state.go("app.home");
}
}
});


I used similar features on alot of frameworks so I'm pretty certain Angular has something like this too. What's the Angular way of doing it?

Thank you.

Ps: I'm not using Angular 2 yet.

Answer

The ui router triggers a $stateChangeStart event, which you can capture:

app.run(["$rootScope", "$state", function($rootScope, $state) {

    $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams, options) { 
        if (toState.name === "auth.signin" && userIsLoggedInLogicHere) {
            event.preventDefault(); // prevent routing to the state
            $state.transitionTo("app.home");
        }
        // else do nothing, it will just transition to the given state
    })
}]);

See this documentation for reference

Comments