One Condition in AngularJS RouteProvider for All Routes, Paths, and URLs

Currently, I am utilizing $routeProvider in order to switch between pages (templates) and controllers when a user clicks on a link.

Here's an example of how it's done:

$routeProvider.when('/profile/', {
        templateUrl: '/app/views/profile.html',     
        controller: 'ProfileCtrl'
    }).when('/timeline/', {
        templateUrl: '/app/views/timeline.html',        
        controller: 'TimelineCtrl'
    }).when('/chat/:username', {
        templateUrl: function(param){
          if(param){
            return '/app/views/chat.html?' + param; 
          }
           return '/';
        },      
        controller: 'ChatCtrl'
    }).otherwise({ redirectTo: '/' });

The issue I'm facing is that there are numerous pages in my application, requiring me to register each URL in the .when condition repeatedly. Additionally, the template URL and controller name are based on the path of the link.

My question is: Is it possible to consolidate all these individual conditions into one single statement?

Something like this:

$routeProvider.when(url, {
    templateUrl: '/app/views/' + url + '.html',     
       controller: url + 'Ctrl'
});

Thank you in advance :)

Answer №1

Give this a shot:

angular.module('myapp', ['myapp.filters', 'myapp.services', 'myapp.directives']).
    config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/page/:name', {
        templateUrl: function(urlattr){
            return '/pages/' + urlattr.name + '.html';
        },
        controller: urlattr.name+'Ctrl.js'
      });
     }
]);

Feel free to test it out. In this scenario, the assumption is that your html page name matches the Controller name and includes 'Ctrl' as a suffix.

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

Unable to retrieve embedded link using fetchText function in casperjs

Exploring the capabilities of Casperjs provides a valuable opportunity to test specific functions across different websites. The website used in this scenario serves as a tutorial illustration. An interesting challenge arises with an embed code that cann ...

Swapping out the standard if/else logic for try/catch error

I'm facing a challenge in removing the then statements from this code snippet and replacing all catches with try/catch statements. I'm struggling to figure out how to handle the then statements. export class WelcomePageContribution implements IW ...

Struggling to handle JSON response in JavaScript

Upon receiving a JSON response from the Amazon API, here is how it appears: { "Result": { "Data": { "Title": "HALO 3 (XBOX 360 - REGION FREE)", "FormattedPrice": "$19.95", "Source": "Product Description", "Content": "The epi ...

An error occurred when attempting to run the command npm run compile:sass, displaying the message: npm ERR! missing script:

Everything seems to be in place with the sass folders and files, so what could be the issue? I have my package.json file set up correctly with the following code: { "name": "starter", "version": "1.0.0", " ...

Sorting tables with jQuery UI sortable() and rowspan功能

Can jQuery UI's sortable() be configured to sort rows based on their "containing" element only? I have a table with rowspanned cells that should only be sorted within their respective spanned columns. var $sortable = $('.nested-sortable tbody&ap ...

The Close button fails to function properly within the Angular UI Modal

I encountered an issue with my Angular UI Modal in this PLUNK. The close button was not functioning as expected because the Modal instance did not have a close method. After some investigation, I found that removing the rendered statement allowed the butt ...

The function persists in outputting a true result, despite the fact that it is expected to output

Currently, I am working on a NextJS project where I have a client-side form. I've been attempting to implement validation for the form by creating a separate function called validateForm(). However, no matter what input is provided, the function alway ...

Can one extract a property from an object and assign it to a property on the constructor?

Currently working with TypeScript, I am looking to destructure properties from an object. The challenge lies in the fact that I need to assign it to a property on the constructor of the class: var someData = [{title: 'some title', desc: 'so ...

Exploring the process of breaking down a substantial string object into manageable key/value pairs using AngularJS

I gathered information from a text file called sample_resume.txt Name: John Doe Phone: (555) 555-5555 Email: [email protected] TARGET To succeed in the field of web development. SKILL SET Development: HTML5, JavaScript, Bootstrap, AngularJS, Rea ...

Retrieve the value from a classic ASP page using an if statement and pass it to

Currently, I am attempting to assign a JavaScript value through ASP. foo('RequestMode', '<%=Request.Querystring("Mode")%>') My goal is to achieve something along the lines of: foo('RequestMode', '<%=if (Reques ...

Fetching information with request query parameters in Node.js

Working on implementing email verification using nodemailer for user sign-ups. The process involves sending out an email containing a link (usually something like localhost:3000/verify/?id=##). After the user clicks the link, I can see that a GET request ...

Ways to extract input values from a specific row in a textbox as users input data

On a button click, I am dynamically adding data to an HTML table using the loadbooks function. When the user clicks on the button, the table is populated with data. <button id="button" onclick="loadbooks()"></button> function loadbooks() { ... ...

Can you explain the functionality of the Json onLoad method and how can I use it to send a response?

function MakeJsonRequest() { JsonRequest.setRequestHeader("Content-type", "application/json"); JsonRequest.send(Data); JsonRequest.onload = function() { ProcessJsonResponse(this.responseText); } } // The Som ...

What is the best way to retrieve a value from an asynchronous method in Node.js that is using promises and also calling another asynchronous method?

I have created two methods for verifying the availability of data in a database and storing the data. The methods are as follows: function IfUserExists(userId) { logger.info(`Checking If ${userId} exists`); return new Promise(resolve => { ...

In React, the error message "Joke.map is not a function" indicates that

export default App I am encountering an error in this code which says joke.map is not a function. Can someone please assist me in finding a solution? I have verified the api endpoints and also checked the function. import { useEffect, useState } from &ap ...

Incorrect date and time displayed

When using this code: <td><% district.created_at %></td> The resulting output is: 2022-08-06T09:14:58.000000Z However, it should look like this: 2022-08-06 09:14:58 The correct format is generated by Laravel 5.3 while the incorrect one ...

Explore the steps for setting up automatic reconnection in socket.io

When establishing a socket.io connection, I use the following code: var socket = new io.connect('http://localhost:8181', { 'reconnect': true, 'reconnection delay': 500, 'max reconnection attempts': 50 }) ...

Angular.js Integration for Custom Single Sign On

I currently have 3 websites built using Angular.js 1.5.8 and I want to integrate them with a single sign-on web application for centralized authentication management. How can I achieve this without relying on external libraries or frameworks? It seems ch ...

display an Angular route on a separate webpage

I am new to using angularjs and I am curious to know if there is a way to display an HTML template based on a specific route inside a div on another page. Allow me to explain with an example. /Employee/Add is a route that displays an add.html template for ...

Apply a common class to all elements sharing the same href attribute

Can someone help me figure out how to add a class to all elements that have the same href as a clicked anchor tag? I understand how to add a class to one element, but I'm unsure about adding a class to multiple elements with the same href. $('. ...