Tips for sending the ampersand character (&) as a parameter in an AngularJS resource

I have an angular resource declared in the following manner:

angular.module('xpto', ['ngResource'])
.factory('XPTO', function ($resource, $location) {
    var XPTO = $resource($location.protocol() + '://' + $location.host() +
    ':port' + '/myservice.svc/gerencia?sigla=:sigla',
        {
            port: ':' + $location.port()
        }
    );
    return XPTO;
})

and I need to make a call to the service with a parameter that includes an ampersand (&), like this:

XPTO.query({ sigla: 'abc&d' }, function (gerencias) {
$scope.gerenciasBuscadas = gerencias;
});

Unfortunately, AngularJS does not encode the & correctly. It sends "sigla=abc&d" instead of "sigla=abc%26d", causing my server to interpret the query string parameter value for "sigla" as just "abc" rather than "abc&d".

Upon examining angular-resource-1.0.7.js, I found the following:

/**
 * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
 * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
 * segments:
 *    segment       = *pchar
 *    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
 *    pct-encoded   = "%" HEXDIG HEXDIG
 *    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
 *    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
 *                     / "*" / "+" / "," / ";"
 */
function encodeUriSegment(val) {
  return encodeUriQuery(val, true).
    replace(/%26/gi, '&').
    replace(/%3D/gi, '=').
    replace(/%2B/gi, '+');
}

Thus, it will encode '&' and then decode it before sending the request to the server. Is there a way for me to customize the URL right before it is sent to the server? Modifying encodeUriSegment is an option, but it could potentially cause issues with other parts of Angular. Any suggestions?

Answer №1

An issue has been identified in AngularJS that needs to be addressed.

To resolve this, I have submitted a pull request. Your assistance in getting it approved is greatly appreciated. You can provide feedback directly on the pull request here.

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

Alert displayed at the center of the browser when the value surpasses the specified number

My webpage retrieves SNMP data using PHP and displays it with HTML, color-coding the values. I want to add a pop-up alert when a value exceeds a certain number. I have attempted different jQuery solutions without success. The PHP code to get the value: ...

Select Menu (Code Languages:CSS, JS, HTML, BBCode)

I'm currently in the process of setting up a BB code for a forum I moderate. Here's the code snippet I'm using to generate a dropdown box that users can add to the signature field of their profiles: <!DOCTYPE html> <html> <d ...

Exploring the Powerful Attributes of Angular Schema Form HTML

I've been exploring the Angular Schema Form documentation in order to add attributes to the elements generated here: https://github.com/Textalk/angular-schema-form/blob/development/docs/index.md I have searched high and low but have not found a solut ...

Having difficulty creating a snapshot test for a component that utilizes a moment method during the rendering process

I am currently testing a component that involves intricate logic and functionality. Here is the snippet of the code I'm working on: import React, { Component } from 'react'; import { connect } from 'react-redux' import moment from ...

Implementing Event Listeners in Vue 3.0: A Guide to Attaching to the Parent Element

How can I attach an addEventListener to the parent element in Vue 3.x? I discovered that you can access the parent by using this code: import { getCurrentInstance, onMounted } from 'vue' onMounted(() => { console.log(getCurrentInstance() ...

What methods can be implemented in Angular JS to avoid the risk of cutting, copying, and pasting in the password and

I have an enrollment form with nearly 30 fields, and I am currently using Angular for validation. Most of my validation is complete, but I am specifically concerned about the password and confirm password fields. Is there a way to prevent users from copyi ...

Adding to the beginning of a list in JQuery mobile

Having trouble figuring out how to prepend my list in jQuery mobile while keeping the divider on top of the most recent item added. I attempted to prepend the newly added item, but it ended up shifting the divider to the bottom instead. function loadScan ...

Tips for modifying the href attribute when a user clicks

Is there a way to dynamically change the value of this link <a href="/Countries/388/10">next</a> without having to refresh the page? For example, if a user clicks on the link, it should update to <a href="/Countries/388/20">next</a&g ...

Highlighting table column when input is selected

I am working with a table where each <td> contains an <input>. My goal is to apply the class .highlighted to all the column <td>s when an <input> is being focused on. Additionally, I want to remove this class from all other columns ...

I'm attempting to retrieve external XML data and showcase it on my HTML page

My goal is to extract any xml tag from the provided sample. However, I am facing an issue with Internet Explorer where I can only retrieve data from the first record. What kind of javascript code should I implement to resolve this problem? <html> ...

Utilizing the URLSearchParams object for fetching data in React

I've implemented a custom hook named useFetch: const useFetch = (url: string, method = 'get', queryParams: any) => { useEffect(() => { let queryString = url; if (queryParams) { queryString += '?' + queryParam ...

The contents of req.body resemble an empty {}

Does anyone know why the req.body is empty in this code snippet? Even though all form data is submitted, it doesn't seem to be recognized in the req.body. Strangely enough, it works perfectly fine in postman. Take a look at the server-side code: con ...

AngularJS special feature: enhance controllers and views by adding notification capabilities

What is the most efficient method for integrating common notification features into necessary controllers in AngularJS? The objective is to establish local notifications that can be effortlessly included or removed from any controller. Key factors includ ...

React Jodit Editor experiencing focus loss with onchange event and useMemo functionality not functioning properly

I'm currently working on a component that includes a form with various inputs and a text editor, specifically Jodit. One issue I've encountered is that when there are changes in the Jodit editor's content, I need to retrieve the new HTML va ...

Exploring AngularJS: Leveraging the $resource.query method with a parameters object

Currently learning angular.js, trying to understand some of the less documented aspects. Let's consider this scenario - there's a server with a search method that accepts query parameters and returns search results, accessible through the GET /s ...

activate a CSS-only modal with JavaScript

Is it possible to trigger a pure CSS modal using JavaScript (jQuery) without the need for a label, so that it activates when a user visits a page? http://jsfiddle.net/h84nubzt/ <label class="btn" for="modal-one">Example</a> <!-- Modal ...

Navigating through different views in Angular 2 using UI Router and ng2 routing directly from

I am currently utilizing the UI-Router ng2 and attempting to change routes after a certain function is triggered. My code snippet looks like this: SomeFunction() { if(condition){ router.navigate(['/newRouteName']); } } It's ...

What is the process for renaming folders with files in node.js?

The current method is effective for renaming a single folder with no files, but it fails when trying to rename a folder containing one or more files. const handleRenameFile = () => { const oldPath = `./${directory}/${fileName}`; const newPath = ...

The Viadeo Social Toolbox seems to be encountering technical difficulties at the moment

I attempted to utilize a Viadeo Social Toolbox, specifically the Viadeo Share Button, but it seems to be malfunctioning in certain browsers? I came across some outdated viadeo share URLs like this: http://www.viadeo.com/shareit/share/?url=${url}&title ...

What is the best way to retrieve the value of a JavaScript variable and display it within an HTML label tag

In my JavaScript code, I'm attempting to retrieve location coordinates using the onchange event and then display those coordinates in a label. I've tried alerting the coordinates successfully, but I'm struggling to update the label using doc ...