Reputation: 645
I want to change the templateUrl on the router provider based on the user permission like the following :
$routeProvider
.when('/',{
if(user)
templateUrl:'app/views/pages/home-page.html'
else if(admin)
templateUrl:'app/views/pages/admin-page.html'
})
I have a query that returns to me the permission of the user, then if the user is admin I should redirect him to admin-homepage ? what is the best practice to do this ?
Upvotes: 2
Views: 320
Reputation: 22405
templateUrl
accepts a function as a value, for dynamic routing values.
From the docs:
"If templateUrl is a function, it will be called with the following parameters:
{Array.} - route parameters extracted from the current $location.path() by applying the current route"
You can either use this function to run your if statement logic, acting like middleware, or apply a function that does the logic, constructs your dynamic template and returns it.
$routeProvider
.when('/', {
templateUrl: _ => { //you're not using a dynamic file name here
let route = 'app/views/pages/';
if (user) route += 'home-page.html';
else if (admin) route += 'admin-page.html';
return route;
}
})
You can take this one step further and actually apply the parameter, which will add a dependency to your URL. Now, the middleware will change here because both accept the same value, so you'll have to change the function to check permissions on both layers, or apply different URL scopes.
Example with $http
. Obviously I don't know your whole schema, to take .isUser
, isAdmin
, and url/for/permissions
as things you need to change.
$http.get('/url/for/permissions/').then(results => {
$routeProvider
.when('/', {
templateUrl: _ => { //you're not using a dynamic file name here
let route = 'app/views/pages/';
if (results.isUser) route += 'home-page.html';
else if (results.isAdmin) route += 'admin-page.html';
return route;
}
})
});
Upvotes: 1
Reputation: 18279
You can achieve this using a routeChange
event (you can add this code to your app.run
):
In your app.run
:
$rootScope.$on("$routeChangeStart", function(event, next, current) {
if(next.$$route.originalPath = '/' && user) {
$location.path('/home');
}
});
Upvotes: 1