AngularJS flexible route parameter

My AngularJS application has routes that can be either:

www.website.com/blog/xyz
www.website.com/blog/xyz/title/other-params

In the second URL, the title parameter is used for readability purposes only and is not mandatory in the URL. Therefore, I have implemented the following AngularJS code for my routes:

$routeProvider
    .when('/blog', {
        templateUrl : url,
        controller : 'blogsHome'
    })
    .when('/blog/:blog_id', {
        templateUrl : url,
        controller : 'blogInfo'
    })
    .when('/blog/:blog_id/:url_params*', {
        templateUrl : url,
        controller : 'blogInfo'
    });

In the above code, I had to include a middle when statement because Angular requires the :url_params parameter and it cannot be empty. Is there a way to avoid having this extra middle when statement?

Answer №1

Inserting * into your project to handle various levels of folders dynamically and using ? for optional paths. However, if you need to deal with multiple layers that are also optional, you can try something like this ?:multipleOptionalParams*?

Give this a shot:

$routeProvider
    .when('/', {
        templateUrl : 'blog.html',
        controller : 'myCtrl'
    })
    .when('/blog/:blog_id/?:url_params*?', {
        templateUrl : 'details.html',
        controller : 'details'
    });

Feel free to check out the Plunker Demo

Answer №2

To modify the sequence of when conditions in order to have the second one come before the third, follow these steps:

Start with the most complex condition first:

$routeProvider
    .when('/blog', {
        templateUrl : url,
        controller : 'blogsHome'
    })
    .when('/blog/:blog_id/:url_params*', {
        templateUrl : url,
        controller : 'blogInfo'
    })
    .when('/blog/:blog_id', {
        templateUrl : url,
        controller : 'blogInfo'
    });

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

Clicking on an absolute HTML element will instantly scroll back to the top of the page

Working on a website, I've designed a custom menu that is hidden with 0 opacity and z-index -1. When a button is clicked, the menu will appear on the screen. You can visit to see the site in action. The issue I'm facing is that every time I cl ...

Implementing inline styles in the HEAD section of a Next.js website

I currently have a blog hosted on Jekyll at , and I'm looking to migrate it to Next.js. My unique approach involves embedding all the styles directly into the HEAD element of each HTML page, without utilizing any external stylesheet files. However, wh ...

Is it possible to remove certain 'css-' class names that MUI automatically applies to its components? (Using Next JS and MUI)

After successfully migrating my create-react-app project to Next JS using the latest version (12.1.0) and following the migration guide at https://nextjs.org/docs/migrating/from-create-react-app, I encountered an unexpected issue. Despite still using MUI a ...

What is the most effective method for nesting loops in NodeJS and Mocha?

Currently, I am attempting to create a loop within a loop in my NodeJS code, but I seem to be getting lost along the way. The results are not as expected - sometimes callbacks are triggered twice and so on. My approach involves using the async module. I wo ...

When an error occurs during form validation, the input field should be highlighted to indicate the mistake

The following HTML code includes validation for Code and Mobile number input fields. The Code field will highlight in red and show an error message when empty or invalid entries are made, while the mobile field will display an error message without changin ...

What causes the AngularJS nested accordion to collapse when data is updated?

While searching for an AngularJS based multi-level accordion to connect with a tree data structure from the back end, I stumbled upon this amazing one https://github.com/LukaszWatroba/v-accordion. It served my needs quite well, although there was one issu ...

What is the proper method for adding a file to formData prior to sending it to the server using a

I came across this tutorial on FormData, but I'm still trying to grasp how the formData object functions. Input Form Example: https://i.stack.imgur.com/h5Ubz.png <input type="file" id="file-id" class="w300px rounded4px" name="file" placeholder=" ...

Checkbox ensemble computes total score

I am currently working on a project that involves multiple checkbox groups, with each group containing 3 checkboxes labeled as (1, X, 2). My goal is to assign a value of 100% to each group, distributed evenly among the checkboxes within it. The distributio ...

Is it possible to alter the background color once the content of an input field has been modified?

I am working with an angular reactive form and I want to dynamically change the background color of all input fields when their value is changed. Some of these input fields are pre-populated and not required. I came across a potential solution on Stack Ove ...

Transferring information through AJAX to the current page using a foreach loop in Laravel 5

As a newcomer to ajax and laravel 5, I am eager to learn how to pass data with ajax to populate a foreach loop in laravel 5 on the same page. <div class="row" style="margin:3% 0px 0px 0px"> @foreach($warung_has_kategoriwarungs['i want pass ...

Creating a dynamic 2D image using HTML5 animation

As a beginner HTML5 developer, I have been exploring ways to create an animated image using multiple jpg files stored in a specific folder on my website. My goal is to design an animation of a rabbit running across the page when a user clicks on a button. ...

Creating an input in Vue3/Javascript that restricts input to only numbers seems to be a challenge

I have a project that involves an input field which should only accept numerical values. Within the template, I've set up an input element with the value bound to a variable and the input event linked to a function that verifies if the entered value ...

Click on a specific image in a table using Cypress with a specific source URL

I need help with a query for Cypress regarding a table of items, each item having active (blue) and not active (black) images. How can I set up this query? Below is an image of the table list: https://i.stack.imgur.com/74qzb.png And here is the HTML code ...

Find items where a certain value matches any of the values in another array and return them

I'm seeking assistance with a specific task. I have an object structured as shown below: SOMEKEY: { "key1": val1, "key2": val2 } Additionally, I have an array that contains string values like this: [stringA, stringB, stringC ...

Simulating dependencies of an AngularJS module in Jasmine unit tests

Currently, I'm facing a challenge with unit testing controller code within a module that has dependencies on other modules. I've been struggling to properly mock these dependencies for testing purposes. I am utilizing the Jasmine Framework and e ...

Detecting changes in a readonly input in Angular 4

Here is a code snippet where I have a readonly input field. I am attempting to change the value of this readonly input from a TypeScript file, however, I am encountering difficulty in detecting any changes from any function. See the example below: <inp ...

Controlling Formatting in ASP.NET

Feeling puzzled by a seemingly simple question with no clear solution in sight. We're attempting to transition an interface to an ASP.NET control that currently appears like this: <link rel=""stylesheet"" type=""text/css"" href=""/Layout/CaptchaLa ...

What are some reasons for the slow performance of AWS SQS?

My current project involves measuring the time it takes to send a message and receive it from an SQS queue. Surprisingly, the average time it takes is between 800-1200 ms, which seems like an excessively long period. Below is the code I have been using for ...

Leveraging the ng-hide property of one controller to adjust the ng-style attribute of another controller through a centralized global controller

Seeking assistance with accessing the boolean value of ng-hide from one controller in order to alter CSS properties of another controller utilizing a global controller. Here is the jsfiddle link: https://jsfiddle.net/dqmtLxnt/ HTML <div ng-controller= ...

Issues encountered while modifying Vue data

In my Vue JS 2 code, I have structured my data as follows: data : { newBus: { name: '', hours: { sunday: '', } } } When setting the data usi ...