Utilizing Angular JS (UI-Router) for Enhanced Functionality with Multiple Optional Parameters

I am currently working on a page that showcases products fetched from a JSON REST web service. To enable filtering based on MinPrice and MaxPrice, I have implemented the use of query parameters on the page. However, I am facing an issue with getting multiple parameters to work seamlessly.

For instance:

Both MinPrice and MaxPrice are optional filters.

When I select MinPrice as 30, the generated URL looks like this:

#/minPriceParam=3

If I then proceed to select MaxPrice as 60, the expected URL should be:

#/minPriceParam=30&maxPriceParam=60

However, the actual result is:

#/maxPriceParam=60 indicating that the minPriceParam=30 part has been lost.

This is the simplified code snippet that I am using:

<a ui-sref="minPrice({ minPriceParam:30 })">   MinPrice 30</a>
<a ui-sref="maxPrice({ maxPriceParam:60 })">   MaxPrice 60</a>

In my JS File:

app.config(function ($stateProvider, $urlRouterProvider) {

$stateProvider

      .state('minPrice', {
        url: '/?minPriceParam&maxPriceParam'

        , controller: function ($scope, $StateParams) 
         {$scope.minimumPrice = $StateParams.min;}
    })

        .state('maxPrice', {
        url: '/?minPriceParam&maxPriceParam'

        , controller: function ($scope, $StateParams) { $scope.maximumPrice = $StateParams.max; }
    })


});

Answer №1

Your code contains some errors that need to be corrected: Firstly, the state parameters should be named minPriceParam and maxPriceParam, not just min and max. Additionally, make sure to include both minPriceParam and maxPriceParam when calling the maxPrice state. See the updated code below.

app.config(function ($stateProvider, $urlRouterProvider) {

$stateProvider
  .state('minPrice', {
    url: '/?minPriceParam&maxPriceParam'
    , controller: function ($scope, $stateParams) 
     {$scope.minimumPrice = $stateParams.minPriceParam;}
})
    .state('maxPrice', {
    url: '/?minPriceParam&maxPriceParam', 
    controller: function ($scope, $stateParams)
    { $scope.minimumPrice = $stateParams.minPriceParam;
      $scope.maximumPrice = $stateParams.maxPriceParam; }
})
});

When calling the maxPrice state in your html, remember to pass the minimum price as a state parameter.

<a ui-sref="minPrice({ minPriceParam:30 })">   MinPrice 30</a>
<a ui-sref="maxPrice({ minPriceParam:minimumPrice, maxPriceParam:60 })"> MaxPrice 60</a>

Answer №2

After reviewing this example, it appears that default parameters can be set within the params section as shown below:

<a ui-sref="eitherPrice()">   MinPrice 30</a>
<a ui-sref="eitherPrice()">   MaxPrice 60</a>

app.config(function ($stateProvider, $urlRouterProvider) {

    $stateProvider
        .state('eitherPrice', {
            params {
                minPriceParam:30,
                maxPriceParam:60
            }            
            , url: '/?minPriceParam&maxPriceParam'

            , controller: function ($scope, $StateParams) {
              $scope.minimumPrice = $StateParams.minPriceParam;
              $scope.maximumPrice = $StateParams.maxPriceParam;
             }
        })

});

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

Error message in Angular about undefined JavaScript function

Struggling to make my Angular 17 project functional with Bootstrap (5) and the datePicker feature. Despite following tutorials, I keep encountering a "ReferenceError: datePicker is not defined" error during the app build process. Here are the steps I&apos ...

I am sending JSON as form data using JavaScript and then accessing it in PHP. During this process, the quotation marks are being replaced with their HTML entity equivalent

After converting an array into JSON, I send it as a value of a text box using the post method. In a PHP file, when trying to print it out, it displays some encoding issues. var json_arr = JSON.stringify(info); The generated JSON looks like this: {"1":"1 ...

The functionality of the Reduce function appears to be malfunctioning

Below is the function I'm utilizing to extract and create issue objects from all documents of type inspection: function (doc) { if(doc.doctype === "inspection"){ for(var i=0; i<doc.issues.length; i++) { emit(doc.issues[i].id, {id: doc. ...

jquery plugin for creating Excel-like filters

I am in the process of creating Excel-like filtering for my dynamic table. To achieve this, I am utilizing a jQuery plugin that can be found at https://github.com/chestercharles/excel-bootstrap-table-filter. The reason why I chose this plugin is because it ...

The initial value in useEffect is not being updated by useState

I am currently implementing a like feature for my web application. The issue lies in the fact that my setLike function is not updating the state even after using setLike(!like). I verified this by adding console.log() statements before and after the setLik ...

Is it possible for JavaScript code to access a file input from the terminal?

When I run the command cat input.txt | node prog.js >result.txt in my terminal, I need to use an input file. This is my code: var fs = require('fs'); var str = fs.readFileSync('input.txt', 'utf8'); str.replace(/^\s* ...

Assistance needed with generating unique IDs in MongoDB

Currently, we rely on MongoDB's built-in ids for all of our unique id generation. However, there are specific cases where we must generate an id for an object before adding it to the database. One potential solution is to create an entry, retrieve th ...

Is there a way to enclose a mention within a unique span tag after highlighting it? Similar to how tags are implemented on platforms such

Currently utilizing an AngularJS plugin called ment.io for incorporating mentions. However, I am having difficulty figuring out how to customize the appearance of the selected mention. For example, in Stackoverflow: https://i.sstatic.net/bZrkh.png Or i ...

Having difficulties utilizing the JSON response efficiently

Currently, I am utilizing datatables to display data and I am looking for a way to fetch language settings from my server efficiently. The challenge lies in formatting the data in a manner that allows this process; I prefer using json format with minimal m ...

Making alterations to the content of a division using getElementById().innerHTML yields no difference

Recently, I've been working on a JS project inspired by a short story from my high school days. The story featured robot crabs living on a small island, and I wanted to create a simulator where players could set the initial parameters and watch as the ...

Tips for efficiently printing invoices on specific paper: Print a maximum of 20 items per sheet, and if it exceeds this limit, continue onto the next page. Ensure the total amount is

$(document).ready(function(){ var j = 23; for (var i = 0; i < j+11; i++) { if (i != 0 && i % 11 == 0) { $("#printSection div").append("<?php echo '<tr><td>fff</td></tr>'; ?>"); ...

Troubleshooting a Buttonset and Javascript Issue

Upon loading the page, I am encountering a JavaScript error in my console: Error: $(...).buttonset is not functioning properly closeVariantForm onclick Is there a way to identify the source of this issue? <p id="vstatus"><label for="varia ...

Unable to conceal tab content upon clicking the identical tab

I recently implemented a tab system with panels that seems to be working well when switching between tabs. However, I'm facing an issue where clicking on the same tab does not hide the corresponding panel and reset the aria attributes as intended. I&a ...

Angular Datatables unable to locate DataTables with Webpack Encore configuration

As I've been updating a Symfony application from version 3.4 to 4.2.2, everything has been going smoothly until I encountered an issue with getting DataTables to work through yarn installation and webpack encore using angular-datatables. The Setup Pr ...

When using Asp.Net TextBox, the focus is lost after inputting the first character

I have created an Asp.Net web form (aspx) that includes a TextBox: <div id="field"> <asp:TextBox Id="Name" runat="server" MaxLength="50"/> </div> Whenever I type characters into the TextBox, I t ...

How can one ensure efficient execution of heavy JavaScript tasks without causing any blocking issues?

Currently, I'm utilizing webgl to load a 3D model and running some code to manipulate it before displaying it. The issue is that this process takes several seconds and completely restricts the user from performing any other tasks during that time. It ...

Having trouble with my bootstrap slider carousel - it's just not cooperating

I incorporated Bootstrap's carousel to display the various courses on my website, featuring three courses at a time before transitioning to the next set of three. However, I am encountering an issue with this setup. Please see the image below for refe ...

Dynamically adjust row height in AG Grid within an Angular application based on the visibility of other columns

My current AG-Grid version is 21.2.1, and I am unable to upgrade it for certain reasons. I have successfully implemented wrapping cell content to ensure all content is visible. Additionally, I have buttons in my application to toggle the visibility of col ...

The attempt to move <script>...<script> code into a .js file is unsuccessful

I've managed to successfully implement oAuth code within script tags in HTML5. However, upon transitioning it to a .js file and attempting to call that file, I encounter errors. Despite trying to emulate the structure of functional js files like app.j ...

Establish attributes within a complex mongoose schema model

Below is the structure of my schema: var userschema = new mongoose.Schema({ user: String, imagen: [{ title: String, name: String, path: String, }] }); Currently, I am attempting the following: ...