Controlling versatile URLs within Angular

I am facing a challenge where most parts of the URLs are optional, with the controller remaining the same. The URL structure is dynamic and changes based on the selected filter parameters. For example, it could be /search, /search/min-1000, /search/max-10000, and so on.

In addition, there are details URLs that are similar to the search URLs but include an id part. For instance, /search/{id}/min-1000, /search/{id}/min-1000/max-10000,

/search/{manufacture-name}/{id}/min-1000/max-10000
, and more.

I'm looking for a way to construct such dynamic URLs using angular-router or angular-ui.

For an example, you can check out this link: http://plnkr.co/edit/70Ihz0nqRjiDOKoEJzRI

Answer №1

To ensure proper functionality, it is necessary to register the parameters for each route defined in the controller. $stateParams effectively generates an object from the URL parameters and injects it into the corresponding route, provided that the parameters are registered with that route.

For each possible scenario, create a route and register all parameters associated with that route:

/search/:id

/search/:id/:min

/search/:id/:min/:max

/search/:id/:min/:max/:type

https://github.com/angular-ui/ui-router/wiki/URL-Routing#stateparams-service

Here is an example similar to your goals from egghead.io (I have provided a plnkr link for easier experimentation: http://plnkr.co/edit/XhWRMipsfn37bEDwC1sT?p=preview

Ensure that each route resembles the following structure:

.state('list.item', {
    url: '/:item',
    templateUrl: 'templates/list.item.html',
    controller: function($scope, $stateParams) {
        $scope.item = $stateParams.item;
    }
})

A video guide on this topic is available here as well:

Answer №2

I have implemented this solution with the use of optional parameters:

$stateProvider
    .state('details', {
        url: '/cars{make:(?:/[^/]+)?}{model:(?:/[^/]+)?}/{id:[0-9a-fA-F]{24}}{postcode:(?:/postcode\\-\\w+)?}{distance:(?:/\\d+miles)?}{minprice:(?:/min\\-\\d+)?}{maxprice:(?:/max\\-\\d+)?}',
        templateUrl: 'js/app/controllers/details/partials/index.html',
        controller: 'DetailsCtrl'
    })
    .state('search', {
        url: '/cars{postcode:(?:/postcode\\-\\w+)?}{distance:(?:/\\d+miles)?}{minprice:(?:/min\\-\\d+)?}{maxprice:(?:/max\\-\\d+)?}',
        templateUrl: 'js/app/controllers/search/partials/index.html',
        controller: 'SearchCtrl'
    })
    .state('searchMake', {
        url: '/cars{make:(?:/[^/]+)?}{postcode:(?:/postcode\\-\\w+)?}{distance:(?:/\\d+miles)?}{minprice:(?:/min\\-\\d+)?}{maxprice:(?:/max\\-\\d+)?}',
        templateUrl: 'js/app/controllers/search/partials/index.html',
        controller: 'SearchCtrl'
    })
    .state('searchMakeModel', {
        url: '/cars{make:(?:/[^/]+)?}{model:(?:/[^/]+)?}{postcode:(?:/postcode\\-\\w+)?}{distance:(?:/\\d+miles)?}{minprice:(?:/min\\-\\d+)?}{maxprice:(?:/max\\-\\d+)?}',
        templateUrl: 'js/app/controllers/search/partials/index.html',
        controller: 'SearchCtrl'
    });

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

What is the best way to initialize React-map-gl with the user's current location as the default latitude and longitude?

Is there a way to render the map with default values of viewport set to user's location without needing to click a locate me button? <ReactMapGL mapboxApiAccessToken={mapboxApiKey} mapStyle="mapbox://styles/mapbox/streets-v11" ...

When using ESLint together with React, you may encounter errors related to `no-unused-vars

I've configured eslint and eslint-plugin-react. After running ESLint, I'm encountering no-unused-vars errors for all React components. It seems that the linter is not recognizing JSX or React syntax. Any solutions? For example: app.js import ...

Issues with data not being successfully transferred between controllers in my service

Presenting my unique service: var CustomService = function () { var filters, charts, subscription; return { getFilters: function () { return this.filters; }, setFilters: function (value) { this.filt ...

Issue with Three JS where the BoundingBox does not update correctly following rotation operations

I am trying to determine the bounding box of a geometry after applying rotations to it. I obtained the rotation code from the sample editor in Three JS: object.rotation.x = xRadians; object.rotation.y = yRdians; object.rotation.z = zRadians This rotatio ...

Utilize formData to upload an image to a database with ajax

I'm struggling with the process of uploading an image from an HTML form. The goal is for the form to send the image name along with other data to a PHP page. Instead of using the serialized function, I opted for formData as it has the capability to h ...

Issues with AngularJS Opening the Datepicker upon Click

Currently, I am developing an application using AngularJS, JQuery, and Bootstrap. In this project, I have incorporated a customized date range picker from www.daterangepicker.com. Issue: The problem arises when I attempt to open the date range picker by c ...

The Angular UI-Router successfully displays the parent ui-view, but the child view containing the templates is not rendering as

If my main HTML file is named index.html and contains the following: <body> <ui-view="home"></home> </body> Within the home view, I am rendering another HTML file called frame.html which includes the following code snippet: <d ...

Check to see if the property of the object does not exist within the array and update as

My goal is to add the variable content into the database content using the $push method, but only if the content.hash doesn't already exist in the database. I want to avoid duplicating information unnecessarily. return shops.updateAsync({ "user": u ...

Tips on invoking a factory method from a different service method in AngularJS

I have a factory method that goes like this.. (function (angular) { "use strict"; angular .module('app') .factory('UserService', ['$rootScope', '$q', function ($rootScope, $q) { ...

Shifting the data label on a pie chart in ApexCharts - what's the trick?

I need help adjusting my data labels to make them more readable by moving them inward. It would be perfect if there is a way to dynamically center them within the slice. https://i.stack.imgur.com/bCelP.png Despite reading the documentation and trying dif ...

Engaging with the crossrider sidepanel extension

When it comes to the crossrider sidepanel, I prefer using an iframe over js-injected html to avoid interference with the rest of the page. However, I am struggling to establish any interaction between my browser extension and the iframe. I believe adding ...

What is the best way to configure a basic firebase ajax call?

I wanted to explore using AJAX instead of set to interact with Firebase. However, when I attempted to do so with the code below in my test.html file, I encountered an error message in the console: XMLHttpRequest cannot load . No 'Access-Control-Allow ...

How can I smoothly navigate to the top of a page using AngularJS?

After receiving an ajax call response using angularjs, I am looking to automatically scroll to the top of the page. The purpose is to bring focus to alert messages displayed at the top of the page upon receiving the ajax response. Appreciate any guidance ...

Is there a quicker method to completely replace an element's DOM with another in jQuery?

Currently, I am utilizing jQuery's AJAX functionality to retrieve new content from the server in JSON format: $.ajax({ url: url, data: { 'ajax': '1', }, dataType: 'json', success: somefunction ...

What is the best way to apply a datepicker to all textboxes with a specific class using jQuery?

I have enclosed multiple fields within div elements in order to specify them with a datepicker for a better user experience. For example: <div class="need-date" > <label>Appointment Date</label> <input id="id_appointment_date" ty ...

Obtain the dynamic identifier of an element within every block using jQuery in a rails application

Let me illustrate my issue with a simple example. I am currently developing a recipe application. Within the show partial that loads via AJAX, I have the following setup: _show.html.erb <% @recipe.ingredients.each do |ingredient| %> <div class ...

Allusion to a intricate data component

In my code, I have a model that is being represented by a class. For example, let's consider the model of a car: export class Car { public name : string; public color: string; public power : number; public service : boolean; } All c ...

The present IP address of the client through AJAX and PHP

This code snippet is on my PHP page: // Setting the timezone to Asia/Manila date_default_timezone_set('Asia/Manila'); $date = date('m/d/Y h:i:s a', time()); if (!empty($_SERVER['HTTP_CLIENT_IP'])){ $ip=$_SERVER['HTTP_C ...

Struggling to retrieve Json data through Ajax in Rails 5

Hey there! I'm currently exploring the world of Rails action controllers with Ajax, and I've run into a bit of a snag. I can't seem to retrieve Json data and display it in my console.log using my Ajax function. The GET method works perfectly ...

Encountering an EACCES error in Ubuntu when attempting to use bower for installation due to permission denial

When attempting to install bower, I used the command... sudo npm install -g bower I received the following output... npm http GET https://registry.npmjs.org/bower npm http 304 https://registry.npmjs.org/bower /usr/local/bin/bower -> /usr/local/lib/no ...