This is the third time this week that I reach some one code that user an AppController like this in it app
<body ng-app="app" ng-controller="AppCtrl">
<div id="inner" ng-view="" ></div>
</body>
And in the controller they redirect to the different parts of the app, like this
.controller("AppController",function({$location}{
if(isUserAthenticated){
$location.path("/home");
}else{
$location.path("/login")
}
});
Is this the correct way to do this. Because it doesn't seem to me. I see this approach very hacky and there should be a right way to do it. Can you guys let me know the best and recommended way to handle this kind of scenarios?
UPDATE: Routing config
// delete $httpProvider.defaults.headers.common["Access-Control-Request-Headers"];
$routeProvider
.when('/app', {
templateUrl: 'views/login.html',
controller: 'AppCtrl'
}).
when('/privados', {
templateUrl: 'views/privados.html',
controller: 'PrivadosCtrl as ctrl'
}).
when('/mensaje/:id', {
templateUrl: 'views/mensaje.html',
controller: 'MensajeCtrl as ctrl'
}).
when('/grupales', {
templateUrl: 'views/grupales.html',
controller: 'GrupalesCtrl as ctrl'
}).
when('/comunicados', {
templateUrl: 'views/comunicados.html',
controller: 'ComunicadosCtrl as ctrl'
}).
when('/contactos', {
templateUrl: 'views/contactos.html',
controller: 'ContactosCtrl'
}).
when('/perfil', {
templateUrl: 'views/perfil.html',
controller: 'PerfilCtrl'
}).
when('/principal', {
templateUrl: 'views/principal.html',
controller: 'PrincipalCtrl as ctrl'
}).
when('/nmensaje/:type', {
templateUrl: 'views/nmensaje.html',
controller: 'NMensajeCtrl as ctrl'
}).
when("/user/password",{
templateUrl:"views/passwordreset.html",
controller: "ResetPasswordCtrl as ctrl"
}).
otherwise({
redirectTo: '/app'
});
The best way that I found to manage the Authentication in an Angular App is the following:
Inside the
.config()
method of your Angular App:then in your routes you could specify which one required the login:
Furthermore you can create an Angular Factory to manage the authentication status of the user.
Note that with this approach you wont need an AppCtrl.