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

Trouble with HTML Contact Page Email Delivery

Hello there, I recently set up a contact page for my html website but unfortunately, it's not sending the messages to my email as expected! You can see what I mean in this screenshot -> https://i.stack.imgur.com/2xPXw.png I'm a bit puzzled b ...

I want to save the information for "KEY" and "textValue" in JSON format and then return it as a response when I make a request to app.get("/api"). How can I achieve this?

Working with GCP Document AI using Node.js and react.js, I have created a JSON structure (var jsonResult) in the provided code. In the for loop, I am extracting key and text value data by using console.log(key); and console.log(textValue);. However, my g ...

Utilizing relative URIs in Node.js request library

I've encountered an issue with my code where node.js is unable to resolve the url: const request = require('request') const teamURL = `/users/${user._id}/teams`; const req = request({ url: teamURL, json: true }, function(error, ...

Immediately Invoked Function Expression in Javascript

const user = { name: "John", age: 30, lastName: "Smith" } (({name, lastName}) => { console.log(name); console.log(lastName); })(user); An error occurred: {(intermediate value)(intermediate value)(intermediate value)} is not function ...

Halt hovering effect after a set duration using CSS or Vanilla JavaScript

Looking for a way to create a hover effect that lasts for a specific duration before stopping. I want the background to appear for just 1 second, even if the mouse remains hovering. Preferably using CSS or JavaScript only, without jQuery. To see my curren ...

The primeVue menubar's active/focused item highlighting feature is not functioning correctly

Currently, we are in the process of developing an electron-based application with the front end primarily coded using Vue.js and primeVue. As a novice, I am encountering issues with the menubar component from primeVue. The problem is that no matter which i ...

Obtaining JSON data in a separate JavaScript file using PHP

I have an HTML file with the following content: // target.html <html xmlns="http://www.w3.org/1999/xhtml"> ... <script src="../../Common/js/jquery-ui-1.10.3.js"></script> <script src="../../Common/js/select.js" type="text/javascript"& ...

How can you decode JSON using JavaScript?

Need help with parsing a JSON string using JavaScript. The response looks like this: var data = '{"success":true,"number":2}'; Is there a way to extract the values success and number from this? ...

Django view receives all data in QueryDict format when using Angular to send data

As I work with Angular 1.4.4 and Django 1.8, I encountered an issue when posting data from Angular to Django view. The data is received in the form of a whole key in the QueryDict. Upon evaluating request.POST in debug mode, it returns: <QueryDict: {u ...

Is there a way to retrieve the title, description, and image URL of a URL through Ajax, similar to how Facebook shares a link?

Currently, I am developing a project that involves allowing users to submit a URL. The system will then extract the title, images, and description from the provided URL and offer the option to toggle between different images. Upon submission, these extrac ...

Create eye-catching banners, images, iframes, and more!

I am the owner of a PHP MySQL website and I'm looking to offer users banners and images that they can display on their own websites or forums. Similar to Facebook's feature, I want to allow users to use dynamic banners with links. This means the ...

How can I display a timer icon in front of text on a Material-UI CardHeader subtitle?

I have a question regarding displaying time in my posts. Currently, I am showing the time as 'a few seconds ago', '2mins ago', 'an hour ago', etc. However, I would like to include a clock icon before this string. Although I a ...

Error: Authorization requires both data and salt arguments

As a novice in NodeJS, I attempted to create an authentication form using NodeJS + express. The issue I am facing is regarding password validation - specifically, when "confirmpassword" does not match "password", it should return nothing. Despite my effo ...

Creating various functions for Joomla's AJAX component development

My component is currently working smoothly with AJAX and mootools. The view.raw.php file contains only one function called display. I've been attempting to add other functions within the component that can be accessed through AJAX, but have been facin ...

Exploring the differences between Yeoman bower installation, npm installation, and grunt

This is my first time working on an AngularJS project and utilizing the Yeoman scaffolding tool (). I'm interested in incorporating fontawesome icons into my app () and I understand that I should use the following command: bower install fontawesome ...

Simple method for securing and unsecuring uploaded files in a directory with the use of AngularJS and a PHP framework

I've been exploring options for encrypting and decrypting files, specifically .pdf files. After researching and experimenting with codes like crypto.js, I'm still struggling to grasp the process. Can someone provide guidance on how to achieve thi ...

Is there a way to organize a list of arrays within a loop based on a specific index within each array in JavaScript?

Greetings, I am currently facing an issue with sorting a specific object of arrays. The structure is as follows: Allow me to provide a clearer example - I am receiving a string from an AJAX call formatted like this: "name|price|blah|blah@name|price|blah| ...

What is the method for adding the total to the title of a highchart?

Is there a way to display this.total in the center of a pie chart title? Here is my code: http://jsfiddle.net/Cp73s/2124/ title: { text: 'How can I show this.total here?', align: 'center', verticalAl ...

Looking to reduce the size of a logo image within a container as you scroll down a webpage?

I've been working on creating a logo section for my website, but I'm struggling to make it shrink as users scroll down and expand back to its original size when they scroll up. I've tried various JavaScript and jQuery functions without succe ...

Show me a list of either only development or production dependencies in npm

When attempting to list only the production dependencies from package.json according to the npm docs, I tried: npm list -depth 0 -prod or npm list -depth 0 -only prod However, npm continues to list both dependencies and devDependencies. Can anyone sugg ...