How can AngularJS handle multiple routes using unique templates while sharing the same controller?

I am currently researching whether I can achieve the functionality described in the title. Here are my initial thoughts:

Let's consider the following routes I have set up:

  .when('/', {
        templateUrl : 'partials/homepage.html',
  })

  .when('/test', {
        templateUrl : 'partials/test.html',
  })

  .when('/page/:pageID', {
        templateUrl : 'partials/page.html',
  })

  .when('/page/single/:pageID', {
        templateUrl : 'partials/page-single.html',
  })

Previously, I was able to include both the templateUrl and controller details in each route, which worked perfectly fine.

However, the application has been updated so that there is now only one controller containing all necessary information, and this single controller must be retained. The new routes will look something like this:

  .when('/:templateName/:pageID', {
       controller: 'myCtrl'
  })

Is it possible for me to dynamically set the template ID from the controller by extracting the templateName parameter? Additionally, how can I handle cases such as /page/single/:pageID where there is a secondary option in the route?

While I can retrieve the templateName parameter and track changes using the $routeChangeSuccess method, I have not found a way to dynamically set the template on the fly.

Any suggestions or ideas to address this challenge would be greatly appreciated.

Answer №1

A possible solution is as follows:

angular.module('myapp', []).
            config(['$routeProvider', function($routeProvider) {
            $routeProvider.when('/:templateName/:pageId', {
                templateUrl: function(urlattr){
                    return '/pages/' + urlattr.templateName + '.html';
                },
                controller: 'YourCtrl'
            });
        }
    ]);

As stated in the AngularJs 1.3 Documentation:

templateUrl – {string|function()} – path or function that returns a path to an html template used by ngView.

If templateUrl is a function, it will receive these parameters: Array.<Object> - route parameters derived from the current $location.path() based on the current route

Answer №2

To improve the structure of your code, consider moving your logic for creating a singleton from your controller to a service. Below is an example that demonstrates how this could be implemented:

app.config(function($routeProvider) {
  
  $routeProvider
    .when('/', {
      templateUrl: 'partials/homepage.html',
      controller: 'SingleController'
    })
    .when('/test', {
      templateUrl: 'partials/test.html',
      controller: 'SingleController'
    })
    .when('/page/:pageId', {
      templateUrl: 'partials/page.html',
      controller: 'SingleController'
    });
  
});

app.provider('appState', function() {
  
  this.$get = [function() {
    return {
      data: {}
    };
  }];

});

app.controller('SingleController', function ($scope, appState) {
  
  $scope.data = appState.data;
  
});

If you still need it to be a singleton controller, you can utilize the ng-controller directive before the ng-view directive to create a $rootScope-like scope for all views. Then, simply include empty function wrappers in your $routeProvider for the controllers.

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

Tips for extracting URL parameter values in React applications

Here is a component that allows for searching: import { ChangeEvent, useCallback, useState } from 'react'; export function SearchComponent() { const [searchValue, setSearchValue] = useState<string>(''); const updateSearchValu ...

Are Bootstrap Input groups inconsistent?

Hey there! I've been working on the sign-in example, but I seem to have hit a roadblock. In my local setup, the top image is what I see in my browser after running the code, while the desired layout that I found on the Bootstrap site is the one below ...

Prevent unchecking a checked list item by clicking on it

Is it possible to prevent the user from unchecking a list item once it has been checked? Your assistance is greatly appreciated! $(".collectioncontainer ul li").click(function(){ $('.collectioncontainer ul li.checked').not(this).removeClass( ...

What is the method for establishing bidirectional communication between separate directives without relying on $watch or $rootScope?

I am currently working on a directive with isolated scope that manages all recording activities such as starting and stopping recordings. Additionally, I need it to call specific callbacks in both directiveA and directiveB when recording starts or finishes ...

Creating a unique custom view in React Big Calendar with TypeScript

I'm struggling to create a custom view with the React Big Calendar library. Each time I try to incorporate a calendar component like Timegrid into my custom Week component, I run into an error that says react_devtools_backend.js:2560 Warning: React.cr ...

Having trouble with triggering a Material UI modal from a Material UI AppBar on a Next.js page

As a newcomer to the world of React.js and Next.js, I am encountering difficulties when trying to open a Material UI modal from a Material UI AppBar within a Next.js page. Most of the code I have implemented here is directly copied from the Material UI we ...

What is the best way to save Vue state in a cookie while transitioning between form steps in a Laravel application

Imagine a scenario where a user is filling out a multi-step form, and we want to ensure that their progress is saved in case they lose connection. This way, the user's data will not be lost between different form steps. In addition to saving each ste ...

Regular expressions: understanding greedy versus lazy quantifiers

Imagine this situation: a = 'one\\two\\three.txt'; The desired output is "three.txt". However, the attempted solution of: a.match(/\\(.+?)$/) is unsuccessful. What could be causing this issue? How can we successf ...

Ensuring that files adhere to the required format, whether they be images

Three separate input fields are being used, each with its own name for identification. A validation method is called to ensure that the files selected in these input fields are not duplicates and that they are either images or PDFs but not both. While thi ...

Resolve problems with implementing dynamic routes in Next.js

I have been learning about Next.js and I am struggling with understanding how to set up dynamic routing. I have the following setup: https://i.stack.imgur.com/uBPdm.png https://i.stack.imgur.com/YYSxn.png "use client" import React from "reac ...

How can VueJS manipulate state with Mutation?

I have set up a Vuex Store that returns data on headers and desserts. The desserts object includes a property called display, which is initially set to false. In my project, I am using a component called Row within another component named Table. The Row co ...

Inject the content loaded from the server into a div element, and insert that div at the

I am trying to insert the div(#loadmore) element inside the div(#boxchatting) element when the content from "result.php" is loaded into div(#boxchatting). Here is the code I used: $('#loadmore').prependTo('#boxchatting'); $('#boxc ...

`To transfer the selected radio button value to a different form field using jquery, follow these steps.`

I need to set either the value no or 1 for the input field name="auth[]" below. <td> send <input type="radio" name="authorized[]'.$c.'" id="send'.$c.'"value="1" checked> </td> <td> no <input label=" ...

Is Selenium designed to work with standalone browsers (using webdrivers) or with browsers that are already installed on the operating system?

I am a newcomer to Cross Browser Testing and have just begun exploring Selenium. However, I am having trouble finding the answers to the following questions on the official site. It would be greatly appreciated if someone could help clarify them for me. ...

What is the best method for submitting a form via ajax that has already been loaded using ajax, all without needing to refresh the current

I have been struggling with a problem for almost a week now. I need to submit a form using ajax, which was already loaded with ajax. I have tried multiple solutions but nothing seems to work. If anyone knows the right approach, I would greatly appreciate y ...

What is the most effective way to include JavaScript code in a PDF file?

What is the process for integrating JavaScript code into a PDF document? I am familiar with coding in JavaScript and would like to learn how to add it to a file in order to perform tasks such as displaying the current date or using a combobox. ...

Selecting DigitalOcean city based on user location in Node.js

Currently, I am implementing Node.js in conjunction with my HTTP server. My goal is to have every user who connects to the server be linked to a real-time game server through WebSockets. Furthermore, I aim for users to automatically connect to the nearest ...

Discovering the method to incorporate a data-icon attribute within select options using vue.js

UPDATE before modification dataIcon: " @/images/flag-ukraine.svg" after modification dataIcon: require("@/assets/svg/flag-ukraine.svg"), notable change with require() I am using Materialize CSS select. When I use a URL for dataIcon ...

React Component Div Containing a Hydration Error

Can someone help me resolve the Hydration error related to a nested div issue? I am working on a component that has two main functions - fetching data and mapping it. However, I keep encountering a hydration error and I'm not sure why it's happe ...

Switch out multiline text with javascript

Could someone assist me with this question? I am attempting to locate and replace specific code within a JavaScript file. The code is included in an AJAX response that contains a significant amount of HTML code. After retrieving the AJAX response, I stor ...