gaurav singh gaurav singh - 4 months ago 7
AngularJS Question

Routing in angularjs based on an attribute

I want to route based on a user type in my angular app.

So if user is Admin, then should be redirected to admin.html and if user then user.html based on the value coming of user type from database after login.

In this I want to add condition:

.when('/dashboard', {
title: 'dashboard',
templateUrl: 'partials/User.html',
controller: 'authCtrl'
})

Answer

you could use .run function and check the user there and redirect to conditional page using $location.

.when('/user', {        
    title: 'dashboard',
    templateUrl: 'partials/User.html',
    controller: 'authCtrl'    
}).when('/admin', {        
    title: 'dashboard',
    templateUrl: 'partials/Admin.html',
    controller: 'authCtrl'    
})

from run function

.run(function($location){
    console.log("run")
    var user = "user";
    if(user === "Admin"){
      $location.path("/admin")
    }else{
       $location.path("/user")
    }
  })

from controller

.controller('authCtrl',function($location){
    console.log("controller")
     var user = "admin";
    if(user === "admin"){
      $location.path("/admin")
    }else{
       $location.path("/user")
    }
  })