Modify the templateUrl in routeProvider according to the user's authorization

Is there a way to dynamically change the templateUrl in the router provider based on user permissions? Here's an example of what I'd like to achieve:

$routeProvider
  .when('/',{
    if(user)
        templateUrl:'app/views/pages/home-page.html'
    else if(admin) 
        templateUrl:'app/views/pages/admin-page.html'
  })

After querying the user permissions, if the user is an admin, how can I best redirect them to the admin homepage?

Answer №1

To accomplish this task, you can make use of the routeSwitch feature (simply insert the following code into your app.run):

Within your app.run:

$rootScope.$on("$routeSwitchStart", function(event, next, current) {
  if(next.$$route.originalPath = '/' && user) {
      $location.path('/dashboard');
  }         
});

Answer №2

templateUrl can be set as a function to handle dynamic routing values.

In accordance with the documentation:

"If templateUrl is defined as a function, it will receive the following parameters:

{Array.} - route parameters obtained from the current $location.path() by utilizing the current route"

This function can be used for conditional logic similar to middleware, or for creating and returning a dynamic template using a separate logic function.

$routeProvider
.when('/', {
    templateUrl: _ => { //no dynamic file name used here
        let route = 'app/views/pages/';
        if (user) route += 'home-page.html';
        else if (admin) route += 'admin-page.html';
        return route;
    }
})

You have the option to further enhance this by incorporating parameters that introduce a dependency to your URL. In this case, adjustments may be required in the middleware as both are accepting the same value. You might need to modify the function to verify permissions on multiple levels, or implement distinct URL scopes.

An example involving $http. Since I lack insight into your complete setup, assume .isUser, isAdmin, and url/for/permissions require customization.

$http.get('/url/for/permissions/').then(results => {
    $routeProvider
    .when('/', {
        templateUrl: _ => { //no dynamic file name used here
            let route = 'app/views/pages/';
            if (results.isUser) route += 'home-page.html';
            else if (results.isAdmin) route += 'admin-page.html';
            return route;
        }
    })
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Telerik RadDatePicker when using ClientIDMode set to "Static"

var StartDate = $('#dtStartDate').val(); var EndDate = $('#dtEndDate').val(); alert(StartDate); alert(EndDate); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <table> <tr ...

The module ~/assets/images/flags/undefined.png could not be found in the directory

When I use the img tag with a dynamic address filled using require, it works well in the component. However, when I try to write a test for it, an error is thrown. console.error Error: Configuration error: Could not locate module ~/assets/ima ...

What is the best approach: Referencing schema within properties or including it as an array in Mongoose?

Consider the scenario where we have two schemas, User and Post. Should we include a reference to User in Post's properties or should we add an array of Post schema inside User schema? Which approach is more efficient in terms of performance and other ...

Guide on leveraging event delegation to trigger a function depending on the id of the clicked element

Although I have experience with event delegation, I am currently facing a challenge in setting up a single event listener that can execute one of three functions based on the ID of the element clicked. Here is the existing code without event delegation: ...

Obtain information about a div element while scrolling

Looking to enhance my social feed page by adding a view count feature for each post. The challenge is figuring out how to keep track of views as the user scrolls down the page. Any suggestions? ...

What is the method for obtaining the div ID's from this form?

This is the scenario I am working on: my app takes the text inputted by the user and exports it to a specific website that contains similar elements. For example, if the user enters a title in the app and clicks a button, the app will transfer that value t ...

Automatically submit form in Javascript upon detecting a specific string in textarea

Just getting started with JS and I have a question that's been bugging me. I have a simple form set up like this: <form method="POST" action="foo.php"> <textarea name="inputBox123"></textarea> <input type="submit" value="Go" name ...

While iterating over the key with a variable in a loop, only one property is displayed consistently instead of four different

Currently, I am working on creating an address book using JavaScript. The problem I am facing is that the properties of my objects are not providing me with the necessary information. I need 4 different properties instead of 4 loops with the same property. ...

Is it impossible to access the length property of an undefined variable?

After developing a function that calculates the length of a string entered into an HTML textbox, I encountered an error when trying to display the result in another textbox. The function is designed to get the value from the 5th textbox on my HTML page and ...

Navigating through the API routes in Express

Within my node API, I have set up two middlewares: app.use('/api', apiRouter); app.use('/*', express.static('public')); The first middleware serves the API endpoints (e.g. /api/users - which returns all users without ent ...

Leaving the pipeline of route-specific middleware in Express/Node.js

My implementation involves a sequence of "route specific middleware" for this particular route: var express = require('express'); var server = express(); var mw1 = function(req, resp, next) { //perform actions if (suc ...

Failing to catch the return value from a stored procedure in ASP Classic

Apologies for the lengthy post, but I wanted to provide all the necessary details. I am facing an issue with a JavaScript function that uses ajax to call some asp code, which then executes a stored procedure to check if a record already exists. Depending ...

Update the network name in the Axios request

Currently, I am utilizing Axios for handling both GET and POST requests. One question that has been on my mind is how to modify the network name: At present, the name serves as the parameter accompanying each request. However, I ponder whether it's f ...

Angular route is completely unresponsive

I initiated the %a{"ng-click"=>"get_destinations(city)"} Nevertheless, it was supposed to direct me to the "destinations" controller, but that wasn't the case There are no errors in the web console – what could be ...

"Exploring the World of Angular and Vue: Harnessing the Power

As a beginner developer, I've been busy familiarizing myself with Angular, React, and Vue. It seems like each of these frameworks use "declarative binding" and "templating". While I grasp the concept of what these are, I'm struggling to see why t ...

Does TypeGraphQl have the capability to automatically format SQL queries?

I am utilizing TypeORM in conjunction with TypeGraphQL. I am curious about the SQL query result that TypeGraphQL provides. For instance, if I have a User Table with numerous columns and a simple resolver like this: @Resolver() class UserResolver { @Q ...

Error message: Can't find Highcharts in (React JS) environment

I have been encountering an error ReferenceError: Highcharts is not defined, and I've been struggling with this issue for a few days now. Can you provide assistance? In my project, I have Dashboard and Chart files where I import the Chart components ...

How come the index variable doesn't show the index in *ngFor loop in Angular 2?

When working with ng-repeat in Angular 1 to display the index, this code is used: <div ng-repeat="car in cars"> <ul> <li>Index: {{$index+1}}</li> <li>Car Name:{{car.name}}</li> </ul> </div> However, w ...

At times, the AngularJS directive may not be invoked

Here is my custom directive: ppm.directive('focusMe', function($timeout) { return { link: function(scope, element, attrs) { scope.$watch(attrs.focusMe, function(value) { if(value === true) { console.log(& ...

Having trouble executing an npm script - getting an error message that reads "Error: spawn node_modules/webpack/bin/webpack.js EACCES"

After installing and configuring Linux Mint, I encountered an error when trying to run my project with the npm run dev command. The error message "spawn node_modules / webpack / bin / webpack.js EACCES" keeps appearing. I have attempted various methods fo ...