Can default query parameters be predefined for a resource in AngularJS?

When working with a simple resource like the one defined below, it is possible to utilize the Receipt.query() method to retrieve a collection from the server. In addition, by calling

Receipt.query({freightBill: 123})
, a query parameter such as freightBill can be added to the request URL like so:
/distribution/inbound?freightBill=123
. How can I include query parameters in this manner, while also setting default values for page, size, and sort within my factory?

The resulting request would appear something like

/distribution/inbound?freightBill=123&page=0&size=20&sort=number,desc

angular.module('webappApp')
  .factory('receipts', function ($http, $resource, $location) {
    var search = $location.search();
    var page = search.page||0;
    var size = search.size||20;
    var sort = search.sort||'number,desc';

    return $resource('/distribution/inbound');
  });

Answer №1

The second argument of the $resource function sets default parameters. For further information, refer to the documentation: Link

angular.module('myApp')
  .factory('orders', function ($http, $resource, $location) {
    return $resource('/orders',{page:0,size:10,sort:'date,asc'});
  });

These defaults can be overridden by passing new values to .query like

Order.query({customerID: 456, size:10, page:1})

Answer №2

In response to my own inquiry, I found a surprisingly simple solution... By attaching the query parameters to the resource path, everything fell into place. When I invoked

Receipt.query({freightBill: 123})
, Angular cleverly added &freightBill=123 to the end of the path. In the absence of other parameters like page, size, and sort, Angular simply included ?freightBill=123 since it was the only parameter.

angular.module('webappApp')
  .factory('receipts', function ($http, $resource, $location) {
    var search = $location.search();
    var page = search.page||0;
    var size = search.size||20;
    var sort = search.sort||'number,desc';

    return $resource('/distribution/inbound?page=' + page + '&size=' + size + '&sort=' + sort);
  });

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

JavaScript Event Listener causing the Sticky Position to Break

I am currently dealing with a situation where I want to create a slide-in side menu that remains sticky. However, when I apply the position: sticky CSS property to my menu container, it causes the entire menu to be displayed (instead of being pushed off th ...

The function 'subController' is not defined and cannot be executed

In my app.js file, I have defined an angular module as follows: var mainModule = angular.module('mainModule ', ["subModule"]); var subModule = angular.module('subModule ', []); In addition to that, I have a separate JS file called sub ...

Having difficulty deleting a checkbox element using JavaScript

My goal is to have a feature where users can effortlessly add or remove checkbox div elements as needed. The code I have written successfully adds and resets checkboxes, but I am encountering an issue when trying to remove them. I am struggling to identif ...

Transforming this JavaScript code to be less intrusive by implementing an event listener for an unidentified ID

As I work on enhancing the functionality of this user interface, I've encountered a challenge with two tabs that require a proper event listener to ensure my JavaScript functions smoothly. This obstacle has been hindering my progress, but as I delve i ...

Selenium web driver showcases its capability by successfully launching the Firefox browser, yet encounters an issue with an invalid address

WebElement searchElement = driver.findElement(By.name("q")); searchElement.sendKeys("Selenium WebDriver"); searchElement.submit(); Displays "Search Results" public static void main(String[] args) { // TODO Auto-generated method st ...

Using Firebase onDisconnect with React Native

I am currently working on a React Native app and I am facing an issue where I need to update the user status to 'offline' in Firebase when the user closes the app. Here is what I have tried: import React, { Component } from 'react' ...

Looking to retrieve an element from an array of objects based on consecutive object properties, I have a specific value to search for

const levels = [ { indexId: 'A', level: 1, name: 'A', parent: '0', }, { indexId: 'A-A1', level: 2, name: 'A1', parent: 'A', }, { ...

After refreshing the page, the console log within the React useEffect function ceases to function

Incorporating the 'useEffect' function to fetch data and store it in the 'ratings' array has proven successful. However, there seems to be an issue when attempting to iterate through the elements of the 'ratings' array for log ...

Executing a function in JavaScript using square brackets

While I was reading through the jQuery source code, I came across this interesting line: jQuery(this)[ state ? "show" : "hide" ](); Is there any particular benefit to using this syntax over the more traditional approach shown below? state ? jQuery(this) ...

Employing ajax with dynamically created buttons in PHP

I'm struggling to figure out what to search for in this situation. I've tried piecing together code from others, but it's just not working for me. My ajax function successfully retrieves data from a database through a php page and displays ...

Obtain the node identifier within the Angular UI Tree component [angular-ui-tree]

Utilizing Angular UI tree to create a relationship between items and categories has been successful in the default setup. However, a new requirement has emerged to incorporate node/section numbering within the tree for managing hierarchy. I attempted to i ...

Can arrays be passed as function parameters in CrossRider without the need to convert them into objects first?

Our team is currently utilizing CrossRider to develop an extension specifically for Internet Explorer. We have a crucial object that is downloaded from , but we are facing an issue where arrays within this object are getting converted into objects with int ...

Functionalities of HTML controls

I currently have a select element in my HTML code which looks like this: <select> <option id="US" value="US"> </option> <option id="Canada" value="Canada"> </option> </select> My requirements are twofold: ...

Modify the length of an array using a number input field

Currently, I am working with an array that contains objects and I want to dynamically change the number of objects in this array based on user input from a number type input box. Whenever the number in the input box is increased, I need to increase the len ...

The 'classProperties' React component module is currently not enabled

Encountering an error while running my react module 'classProperties' isn't currently enabled (44:11): } 43 | // componentDidUpdate or try this > 44 | onClick = (e) => { | ^ 45 | e.preventDefault(); 4 ...

I'm looking for an AngularJS module that functions like the NodeJS request library. Can anyone point

Hello everyone, I am in search of an AngularJS module that streamlines HTTP/HTTPS requests and includes additional features similar to the popular request library for NodeJS (https://github.com/request/request) The default $http uses promises, which can ...

Display JavaScript and CSS code within an Angular application

I am working on an Angular 1.x application (using ES5) where I need to display formatted CSS and JS code for the user to copy and paste into their own HTML file. The code should include proper indentations, line-breaks, etc. Here is a sample of the code: ...

Only show the directive methods when using "ng-if"

I am facing an issue with the Opentoke Library directive, particularly when I use the ng-if. The reason for implementing the ng-if is that WebRTC is not supported on IOS devices, so it displays an alert after the DOM has loaded. <div class="opentok" ng ...

What is the best way to emphasize a specific data point within a chart created with chartjs, especially when the data is sourced from a JSON

// Here I am retrieving another set of data in JSON format from a PHP file $(document).ready(function () { showGraph(); }); function showGraph() { $.post("phpfile.php", function (data) { console.log(data); var name = []; v ...

Troubleshooting the issue of browser prefix injections not functioning properly in Vue when using the

I've spent an entire afternoon on this issue and I'm completely stuck. After realizing that IE11 doesn't support grid-template, I learned that I need to use -ms-grid-columns and -ms-grid-rows instead. I am attempting to generate CSS and inje ...