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

Communication between React.js and Node.js in VS Code

I recently started learning React and node js. I managed to create a simple "Hello World" project in reactjs, which works perfectly. App.js import React, { Component } from 'react'; import logo from './logo.svg'; import './App.cs ...

Make sure to consistently show the rating bubble within the md-slider

I am currently exploring the functionality of md-slider in its md-discrete mode. However, I would like to have the slider bubble always visible on the screen, similar to this: I do not want the slider bubble to disappear when clicking elsewhere. Is there ...

Interact with AJAX form to dynamically display result data in the intended DIV

Seeking assistance from experienced JS users! Although most features are functional, including results being returned and forms submitting to MC database, I am encountering an issue where the result html is appearing in the incorrect DIV. Instead of displ ...

Creating wrapped text in Three.js

Is there a way to wrap a Text3d object around a 3D or 2D Path in Three.js? I have looked into some tutorials for r.49 of Three.js and it appears that the current version does not have support for this feature. While I am able to create the text and extru ...

When attempting to add mp3 files to a Vue/TypeScript application, a "Module not found" error is triggered

I am encountering an error while trying to import .mp3 files into my Vue/Typescript app. Upon running 'npm serve', I am presented with the following message: ERROR in /Users/***/***/application/src/components/Sampler.vue(80,16): 80:16 Cannot fin ...

Learn how to showcase the current date by utilizing JavaScript arrays and the getDate method!

I have been struggling to format the date as follows: "Today is Sunday, the 31st day of March in the year 2019." I am working with JavaScript in an HTML5 document. Below is the code I have so far, and I would appreciate any help. I prefer not to rely on ...

Obtaining information from node.js module to the server.js script

I am attempting to extract data from a function within a node module, which returns a JSON object. My goal is to display this JSON object in a router located in my server.js file. This is how I am trying to export it: // Function Export exports.g ...

Manipulating CSS animations through JQuery

Currently, my animation is triggered by a :hover event. However, I would like to change it so that the animation starts when a button is clicked. Can someone guide me on how to manipulate the CSS using JQuery? //CSS .mouth{ top: 268px; left: 273px; ...

Retrieve a variety of items and pass them to a view using the mssql module in Node

I'm facing an issue while trying to retrieve data from multiple tables and pass them to my view. Below is the snippet of code I've written that's causing the error. router.get('/', function(req, res, next) { sql.connect(config ...

Incorporate a fontawesome icon into a dynamically created button using ajax

Is it possible to insert fontawesome icons into a button created using this code snippet? $.each(response, function (i, item) { trHTML += '<tr><td>' + item.name + '</td><td>' + "<input type='button&apo ...

Changing the way in which text is selected and copied from a webpage with visible white space modifications

After working on developing an HTML parser and formatter, I have implemented a new feature that allows whitespace to be rendered visible by replacing spaces with middle dot (·) characters and adding arrows for tabs and newlines. You can find the current ...

How can I efficiently create a suffix using this JavaScript code?

Take note that the code displayed below showcases the array in the console, rather than in the snippet output var names = ["maria", "mary", "marks", "michael"]; function add_suffix(names) { var suffixes = []; for (var i = 0; i < names.length; i+ ...

Tips on accessing the v-model value with a parameter in VUE

Looking to access the v-model value using a parameter, I attempted the following code: <template> <div v-for="(item, idx) in data"> <input :id="item" :v-model="item"></input> <button @click=&q ...

Binding data to an MVC grid component

I am working with asp.net mvc3.0 razor framework and using an html Table to populate data from ViewBag based on the selected option in a dropdownlist. public ActionResult Index(GetFileName fn) { .... ViewBag.Grid1Data = dt; return View(); } Initially, th ...

A guide on incorporating oAuth 2.0 into Tizen

Currently, I am in the process of incorporating Google authentication using oAuth 2.0 in Tizen. I am following the guidelines provided here. Despite successfully obtaining the user code as instructed in the link, I keep receiving an invalid request error w ...

Retrieve a text file using FTP asynchronously and utilizing Promises in Node.js and AWS Lambda

Utilizing a single Node module called basic-ftp, I am tasked with downloading a txt file in AWS Lambda and storing it in the /tmp/ directory within the Lambda function. The goal is to manipulate the txt file and its contents outside of the FTP function. ...

Safari Glitch in Bootstrap 4

For a simplified version, you can check it out here: https://jsfiddle.net/dkmsuhL3/ <html xmlns="http://www.w3.org/1999/xhtml"> <title>Testing Bootstrap Bug</title> <!-- Bootstrap V4 --> <link rel="stylesheet" href="https://m ...

Encountering an "AJAX not a function" error while using the d3/flask interface

Hey there! I'm new to the world of JavaScript and AJAX. Take a look at this d3 function I've been working on: var node = g.selectAll(".node") .data(root.descendants()) .enter().append("g") .attr("class", function(d) { return "node" + ...

Ways to stop React from refreshing the page upon clicking the submit button

Is it possible to prevent a React component from reloading the page when a submit button is pressed? Here is an example of component code: class MyComponent extends React.Component<IEditCampaignStateProps & IEditCampaignDispatchProps, EditCampaignStat ...

What is the significance of declaring a constant array in JavaScript?

Does declaring an array as a constant in JavaScript prevent it from changing size, or does it mean that the values inside the array cannot be modified? handleClick(i) { const squares = this.state.squares.slice(); squares[i] = 'X'; this.setState( ...