Managing a variable number of parameters is now made possible with the new

In my code, I have a sentence that looks like this:

.state('category', {
    url: '/categories/:parameter',
    templateUrl: 'templates/common/categories.html',
    controller: 'categoriesCtrl',
    resolve : {
    categoryList: ['Products', function (Products) {
        return Products.listByCategories($stateParams.parameter);
    }]
    }
})

It's for a simple web shop where products are listed based on categories. The issue is that the number of categories needs to be dynamic. For example, I might request:

/categories/shoes
/categories/shoes/man/
/categories/shoes/man/running
/categories/shoes/man/running/nike

The parameter must adjust dynamically, but I'm not sure how to achieve this. Can someone provide some guidance? Thank you!

Answer №1

There are two options to consider:

Option 1 (not recommended but possible):

$stateProvider.state('category', {
    // You can modify all patterns, but ensure {0, x} allows for empty spaces between slashes.
    url: '/categories/{item:[a-z0-9\-]{0,8}}/{gender:[a-z]{0,6}}/{sport:[a-z]{0,12}}/{company:[a-z0-9]{0,8}}',
    controller: function($stateParams) {
        console.log($stateParams);
    }
});

You can use:

  • /categories/shoes///
  • /categories/shoes/man//
  • /categories/shoes/man/running/
  • /categories/shoes/man/running/nike

Option 2 (preferred):

$stateProvider.state('category', {
    // The pattern can be modified except for \/
    url: '/categories/{details:[a-z0-9\/\-]{0,20}}',
    controller: function($stateParams) {
        console.log($stateParams);
    }
});

Now you can use any combination starting with /categories/:

  • /categories/shoes/man/running/nike

Simply utilize the split() method and specify that:

  1. Key 0 will contain items.
  2. Key 1 will contain gender.

In cases where gender is input instead of item, compare key 0 to the

items whitelist(array with items)
. Enjoy!

Answer №2

In my experience, I have observed that categories are often separated by a '-' or a '+' instead of slashes. This method is preferred because slashes can cause issues with URL routers, especially in the case of Angular.

Alternatively, you could consider parsing the entire URL and handling the slashes manually. However, using a '-' or '+' allows you to parse the directory as a string and then split it based on the delimiter to generate a list of categories for searching purposes.

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

When creating a primitive array object using the 'new' keyword, which class constructor gets invoked?

When we attempt to create arrays like: int[] arr = new int[10]; An object is generated in the Heap each time we use the keyword new, utilizing the constructor of the relevant class, and then the address of this object is assigned back to the reference va ...

What's the issue with reducers receiving a Function instead of an Object in Redux?

I encountered an error in my react and redux project but I am unable to figure out how to fix it. Here is the error message: The reducer received unexpected type "Function" as the previous state. It was expecting an object with keys: "posts", "sidebar" ...

Using Django for Underscore and Backbone templating

When I define my JavaScript templates within: <script type="text/template"> </script> they are not rendered in the HTML (I don't see them on the page) in my Django application. Could one of the filters or middlewares I have declared be e ...

What are the best practices for linking promises in a intricate sequence of resource loading?

When working with Angular code, I have a series of chained promises that look like this: // Defined function in the LoaderService module. var ensureTypesLoaded = function(){ return loadContainerTypes($scope).then(loadSampleTypes($scope)).then(loadProje ...

The current status of Dropzone.js is in a pending state, preventing the upload of any

I have integrated Multer in the back-end for file upload handling and Dropzone.js in the front-end. Testing my back-end code with Postman works perfectly, but when using Dropzone, the status remains pending and the file does not get uploaded. After waiting ...

What purpose does the <noscript> tag serve in React?

Recently delving into the world of React, I've been working on a simple application by following this tutorial: https://reactjs.org/tutorial/tutorial.html. I've started modifying the code to suit my own project. While inspecting my HTML, I notic ...

Tips for achieving JSON formatting with JavaScript or jQuery

To achieve the desired output format, I am required to transform the provided input json. input json: [ { "key a": "value alpha" "key b": "value beta" "key c": "value gamma& ...

Utilizing Material-UI Select for creating a number range dynamically

Seeking a solution to create a select element using material-ui that offers a range of numbers from 0 to 20,000,000 in increments of 25,000. Currently, I have accomplished this using a for loop. for (let price = 0; price <= 20000000; price = price + 250 ...

When an image in AngularJS is clicked, it should display a corresponding list

I'm brand new to Angular development. This is my very first solo project. My goal is to design a page where clicking on an image will display a list of items below it. For example, check out this link for reference: I've searched online for so ...

The PropertyOverrideConfigurer encountered an issue while processing the key 'dataSource' - The key 'dataSource' is invalid, it was expecting 'beanName.property'

During the installation of Sailpoint on Oracle, the configuration properties are as follows: ##### Data Source Properties ##### dataSource.maxWaitMillis=10000 dataSource.maxTotal=50 dataSource.minIdle=5 #dataSource.minEvictableIdleTimeMillis=300000 #dataSo ...

The termination character in Java

I encountered a simple problem while working on a coding question: The task was to eliminate certain characters from a character array in Java, and the approach seemed quite clear: static void remove_char(char[] arr, char c){ int r = 0; for (int ...

Constant Initialized Array of Structures within a C++ Class

When working with const arrays in a class namespace in C++, there is a limitation where you cannot define them as private. For example: class c { private: struct p { int a; int b; }; static const p pp[2]; }; const c::p pp[2] = { {1,1},{2 ...

JavaScript Array Counting Within Nested Arrays

I'm currently facing a challenge that I need help in resolving: Here is the structure of an array that I am working with: [ [{rivals: ['player1','player2'], winner: "player1"}], [{rivals: ['player1','player3'] ...

Using Pointers to Pass a Dynamically Allocated Array in C++

Seeking help with C++ - I'm new to this topic and struggling with dynamically creating an array based on user input using a pointer. When passing the array to a function, I feel like something is not quite right as there is no dereferencing happening. ...

Transform numeric values into their equivalent word representations (implementing loops and arrays)

Is there a way to write a program that can convert numbers into word-numbers using loops and arrays? For example: input: 1532 output: One Five Three Two My attempted solution looks like this: class NumberToWord { public static void main ...

Fuel Calculation - Unable to pinpoint the error

My JavaScript Code for Calculating CO2 Emissions I'm working on a program that calculates how much CO2 a person produces per kilometer. This is part of my school project and I'm still learning, so please bear with me... I also just signed up on ...

Updating a file using HTML5's FileWriter

I've been experimenting with the HTML5 FileWriter API in order to save my webapp's state. I have a snippet of JavaScript that regularly triggers the FileWriter.write function to achieve this, resulting in multiple calls to the write method over t ...

What causes the slash URL to behave differently than other URLs when running through the middleware of NodeJS?

When I type http://localhost:3000/product into the browser, why do I see output for both '/' and '/product'? Take a look at this code snippet below. const express = require('express'); const app = express(); // http://loca ...

Get the most recent 5 messages that haven't been read yet

I am attempting to utilize the GMAIL API in conjunction with JavaScript to extract unread messages from a user's inbox, specifically the last 5 messages. After successful login using the G+ API, I have been trying to employ jQuery's $.get method ...

Utilize Devextreme's dxDataGrid component to transmit the selected RowData to a function upon clicking a button within that particular row

I am utilizing the dxDataGrid user interface widget from the Devextreme product. My goal is to transform one of its columns into a clickable button. Here is my progress so far: Field Configuration { dataField: 'LetterNumber', caption: ' ...