Angular Routing for a specific page path

I am currently in the process of working on a project using the MEAN stack and I have encountered an issue with getting a specific template to display on a particular URL.

Currently, when users visit www.myurl/catalog, it loads the catalog.html template, similar to any other /catalog?category=productType URL.

My goal is to have the catalogSpecific.html template load when users visit /catalog?category=specificProductType. However, at the moment, the catalog.html template takes precedence over the catalogSpecific.html template. I have not been able to find much information on this specific problem, so any assistance would be highly appreciated.

Here is how my routes are set up:

app/front/app.js

angular.module('app', ['ngRoute',
                    'app.LandingModule.controller',
                    'app.CatalogModule.controller',
                    'app.ProductModule.controller',
                    'app.HeaderModule.directives',
                    'app.FooterModule.directives'
                    ])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider
.when('/', {
  templateUrl: 'html/landing.html',
  controller: 'LandingController'
})
.when('/catalog', {
  templateUrl: 'html/catalog.html',
  controller: 'CatalogController'
})
.when('/catalog?category=specificProductType', {
  templateUrl: 'html/catalogSpecific.html',
  controller: 'CatalogController'
})
.otherwise({
  redirectTo: '/'
});
}]);

Answer №1

UPDATE: It turns out I was mistaken regarding the limitations of the default router. Hadi pointed out in their comment that you can actually use a function to dynamically generate template URLs based on the current route.


In my understanding, achieving the desired routing behavior isn't directly possible with the standard Angular router.

There seem to be two potential paths forward from here:

1: Gain proficiency in utilizing the ui-router library (available at this link)

2: Implement a custom controller/page for all routes starting from /catalog, which manually parses route parameters and redirects accordingly. (Refer to this documentation on $routeParams)

Answer №2

Consider using the templateUrl function in this way. Please note that I have not tested it yet.

  templateUrl: function($location){
     if($location.category)
         return 'html/catalogSpecific.html';
       else
          return  'html/catalog.html'; 
 },

See Demo Here

Answer №3

Thanks to Hadi's guidance, I managed to solve this:

    .when('/catalog', {
  templateUrl: function($location){
            if($location.category == "specificProductType") {
            return 'html/catalogSpecific.html';         
        } else {
            return 'html/catalog.html';
       }
},
  controller: 'CatalogController'
})

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

Manipulating strings within strings with JavaScript

It's been a strange discovery I made while working with JavaScript. Whenever I try to assign a two-word string to a CSS property, like setting the fontFamily property of an HTML element to "Arial Black", it ends up looking something like thi ...

How can I make an image the background on a webpage when clicking the mouse?

I find myself in a predicament without any code to guide me. The idea seems simple - I desire the ability to select an image from a collection and set it as the background image for the webpage. While I understand that JavaScript is essential for this tas ...

Encountering an unusual issue: Unable to access undefined properties (specifically 'get')

I'm struggling to get the order history screen to display the order history of a specific user. Every time I navigate to the path, I encounter the error mentioned in the title. I double-checked the path for accuracy and made sure there are no spelling ...

Acquiring an alternative data structure in JavaScript or JSON

When clicking on a div with different attributes, I am attempting to retrieve a data object. Here is an example: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> var locA = { "fro ...

Is there a way to temporarily change only the appearance of a website's design from the client-side, even if I don't have direct access to it?

On a typical website, there is a CAPTCHA and a form that requires the correct CAPTCHA input before allowing access to certain information. However, as I do not have ownership of this site and find its design lacking, I am considering modifying its layout f ...

Interact with Javascript by clicking and dragging to spin around

Looking for assistance with rotating an element (like a dial) using click and drag. The concept is there, but there are some glitches that need fixing. You can view my current example here: https://jsfiddle.net/o5jjosvu/ When clicking and dragging inside ...

The absence of the 'Access-Control-Allow-Origin' header is reported even though it is actually present

I have been attempting to send a POST request from one website to my own site. Despite allowing CORS access explicitly, every time I try to make the actual POST request, I am faced with the No 'Access-Control-Allow-Origin' header is present on th ...

What is the best way to verify the application's authenticity when making AJAX requests?

I have the below Code written in AngularJs, but I need to ensure that the authenticated app is sending requests to the backend. How can I achieve this? resp.get Update = function () { //return $http.get(urlBase); return $http({ ...

What is the process for importing the required dependencies for the maps module in react-svg-map?

Exploring interactive maps led me to discover the project react-svg-map. As I followed the example provided, a certain issue caught my attention: import Taiwan from "@svg-maps/taiwan"; The developers mentioned that they have separated the map&ap ...

Unable to maintain checkbox state after page reload in React

I am currently working on creating a to-do list application using React and Material UI. Everything is functioning well except for the checkbox state. I am storing each to-do as an object in an array called todoList in local storage, like this: todoList i ...

Utilize a variable within a regular expression

Can the variable label be used inside a regex like this? const label = 'test' If I have the regex: { name: /test/i } Is it possible to use the variable label inside the regex, in the following way? { name: `/${label}/i` } What do you think? ...

How can I display a specific element from a child Component when the main Component is clicked on in React?

I am currently working on my first React project and facing a challenge. I have a dropdown list on my main homepage that displays specific details when clicked. However, I am struggling to show the right corresponding detail (for example, black&white paren ...

Error: ResizeObserver is not defined when using Gatsby with nivo charts

I incorporated @nivo/pie using "gatsby": "^3.13.0", but encountered an error during the gatsby build process. WebpackError: ReferenceError: ResizeObserver is not defined. The version of Nivo being used is "@nivo/pie": "^0 ...

How can we pass the onClick prop from a child component to a parent component in React with Typescript?

Currently, I am utilizing React along with TypeScript. I am curious about the process of passing an event from the parent component to a child component using props. Here is an example for better understanding: parent.tsx const ParentComponent: React.F ...

What is the best way to access an excel file using JavaScript and Protractor?

Is it possible to read an Excel file dynamically in JavaScript and iterate through cell values using row and column counts, without converting it into a JSON object? I have searched through several posts on Stack Overflow but have not found a solution yet. ...

Prevent a module from initializing upon importing in JavaScript

I'm currently developing a notification system and facing challenges on how to instantiate a function dynamically rather than just when it is imported. For instance: Here is the structure of my notification function: const sendNotification = async ( ...

How can I change a textarea to uppercase?

I'm looking to create a textarea that automatically types in all capital letters, regardless of the user's input or whether they are holding down the shift key. I want it to accept any input and convert it to uppercase on the fly without showing ...

Moving an array in AngularJS from one file to another

As someone new to AngularJS, I am facing an issue with integrating two separate files that contain modules. Each file works fine individually - allowing me to perform operations on arrays of names. However, when switching views, the arrays remain stored un ...

Is it possible for a Discord bot to retroactively respond to and interact with previous messages?

This could be used for a voting system related to images. My idea is this: After 10 seconds, my bot restricts the ability of @everyone to send messages, but at the same time adds a reaction to all the messages that have been sent in, allowing people to v ...

directive to prevent submission of a form

I am looking to dynamically add the class disable when form.$valid is false. The first submit button outside the directive works fine, but I am struggling to access the form state within the directive without hardcoding the form name. It needs to be a re ...