AngularJS' $rootScope is experiencing issues with creating internal variables

My app utilizes $rootScope.requestObj to store key-value pairs representing filters.

Throughout the entire application, $rootScope.requestObj is considered a singleton and behaves as expected.

However, when I call an external API, I have a service that takes in $rootScope.requestObj as a parameter.

Below is the code snippet:

 function requestHandler(obj /*In my controller I am passing $rootScope.requestObj*/) {

        var internal_object = obj;

        console.log('BEFORE FILTER = ', JSON.stringify($rootScope.requestObj));

        Object.keys(internal_object).forEach(function (key) {
            if (key != 'limit' && key != 'offset' && key != 'cities') {
                internal_object[key] = null;
            } else {
                if (key == 'limit') {
                    internal_object[key] = REQUEST_LIMIT.simplyRETS; //outputs 500 that is simplyRETS limit for a request.
                }
            }
        });
        console.log('AFTER FILTER = ', JSON.stringify($rootScope.requestObj));
       //Rest of the code, I basically serialize the internal_object and send it
       //as params of a $http.get request.

Although I pass $rootScope.requestObj to my internal_object, I never directly modify $rootScope.requestObj. Yet, the initial console log shows this:

Note the 'maxprice' value.

BEFORE FILTER =  {"type":null,"minprice":null,"maxprice":2,"minbeds":null,"maxbeds":null,"minbaths":null,"maxbaths":null,"minarea":null,"maxarea":null,"limit":500,"offset":0,"cities":"Aventura","q":null}

The subsequent log reveals this =

AFTER FILTER =  {"type":null,"minprice":null,"maxprice":null,"minbeds":null,"maxbeds":null,"minbaths":null,"maxbaths":null,"minarea":null,"maxarea":null,"limit":500,"offset":0,"cities":"Aventura","q":null}

During the iteration where I clear everything from INTERNAL_OBJECT except limit, offset, or cities, $rootScope.requestObj inexplicably changes and displays a different value.

In this case, I am only focusing on maxprice for simplicity. I'm using JSON.stringify() to capture the current state of the object's value.

I suspect there may still be some connection between my internal_object and $rootScope.requestObj. However, I'm unsure why this occurs and how to prevent it.

Edit

I was confused because I assumed var internal_object created new memory space. As clarified, it actually created a reference.

Answer №1

As a matter of fact, this is the intended functionality. By utilizing "var internal_object = obj;", you are essentially assigning the memory address of obj to internal_object, allowing for any alterations made to internal_object to reflect on obj. In the case of using angular, opt for "var internal_object = angular.copy(obj);" instead. This way, the object will be duplicated rather than sharing the same memory reference.

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

Assigning index values to child rows in AngularJS: a step by step guide

One of my requirements involves assigning index values to child rows. The structure includes group rows with child rows underneath. Currently, I am using ng-repeat along with $index for the children as shown below: HTML code: <table ng-repeat="nod ...

Ending a connection to MS SQL server in node.js with mssql library

In my journey to write a node.js script for querying an MSSQL database, I find myself navigating the realm of JavaScript, node.js, and VSCode with limited SQL knowledge. While I have managed to piece together working code, the issue lies in the connection ...

Identifying Flash content in a unique way

In my dynamic page (let's call it myFlashContainer.jsp), the Flash content changes based on the link that is clicked. The code responsible for rendering the Flash looks like this: <object height="100%" align="l" width="100%" id="player" codebase= ...

What are the steps to making a textfield editable with JavaScript and HTML?

My textfield is currently populated with values from the database and is functioning perfectly. I would like to implement a checkbox feature that, when clicked, will clear the textfield of the database values, allowing the user to input new values. If t ...

Combining CodeIgniter4 with Vue.js and Webpack's devServer to handle CORS issues

Exploring Vue & CodeIgniter 4, starting from https://github.com/flavea/ci4-vue. No matter what I try, I encounter a persistent CORS error in dev mode: Access to XMLHttpRequest at 'http://example.com/public/api/book/get' from origin &apo ...

Passing a JSONArray to a webview using addJavascriptInterface can provide valuable data

Within my Android app assets, I have stored an HTML page that I want to display using a WebView and add parameters to the webpage. To achieve this, I populated all the values in a JSONArray and utilized 'addJavascriptInterface' to incorporate th ...

The onclick event is malfunctioning in Chrome when dealing with data driven by SQL

<select id='city' name='city' > <?php $dbcon = mysql_connect($host, $username, $password); mysql_select_db($db_name,$dbcon) or die( "Unable to select database"); $city_query = "SELECT city,county FROM citycatalog order by city ...

Discovering the present width of an Angular element after it has been eliminated

Imagine you have a horizontal navigation bar coded as follows: HTML: <ul> <li ng-repeat="navItem in totalNavItems">{{name}}</li> </ul> CSS: ul, li { display: inline-block; } The data for the navigation items is fetched from thi ...

Verify Departure on External Links within Wordpress

Let me set the stage for you: We're dealing with a bank website here. So, whenever a user wants to click on an external link (could be to a Facebook page or a partner website), we need to have a notification box pop up saying "You are about to lea ...

Escaping JSON Keys with Operators in AngularJS

Can you help me with an AngularJS syntax question? { "key-part": "value-part" } is a valid JSON object. However, in AngularJS, {{ x.key-part }} is an expression that returns 0 instead of "value-part". Do you know how to escape the '-' in this ca ...

Experiencing an infinite loop due to excessive re-renders in

I'm receiving an error and unsure of the reason. My goal is to create a button that changes colors on hover. If you have a solution or alternative approach, please share! import React, {useState} from 'react' function Login() { const ...

Enforce the rejection/resolution of a promise

Currently, I am in the process of validating a file upload by extracting the contents of a manifest file from within a zip file. Utilizing JSZip for this purpose, I aim to halt the file upload procedure based on specific conditions. How can I effectively t ...

An elusive static image file goes unseen within the realm of node.js/express

I am encountering an issue with serving static files in Express on Node.js. When I request a .css file from the server, everything works fine. However, if I try to load an image such as a jpg or png, it just shows a blank white page without any error messa ...

Populate tabulator table with nested data fetched through an ajax call

I received an API response from a store in JSON format containing three records at the first level. The structure of the response includes data, error_no, msg fields. Within the data field at the second level, I have data.items, data.total_pages, data.to ...

Spin the Three.js camera in a circular motion along the Y-axis

I'm feeling a bit puzzled about this one :S I've written a code that allows my camera to rotate only halfway. I can move the camera along half of a circle using mousemove events, but I actually want it to be able to complete a full rotation :) ...

An introduction to the basics of AngularJS, AJAX, and ASP.NET MVC

I am struggling with creating a simple AngularJS example that makes an AJAX call to an ASP.NET MVC action method. I have tried various approaches but haven't been successful yet. Below is the code snippet I have been working on... The ASP.NET MVC act ...

Error: Primefaces ajax status failure (dialog has not been defined)

I incorporated the same code found on primefaces.org, specifically this link: http://www.primefaces.org/showcase/ui/ajaxStatusScript.jsf <p:ajaxStatus onstart="statusDialog.show();" onsuccess="statusDialog.hide();"/> <p:dialog modal="true" ...

Excluding Fields from Wagtail API Responses: A Quick Guide

When referring to the Wagtail documentation, there is a specific section dedicated to the exclusion of certain fields from the API (). The focus is on how to remove these fields from the perspective of the API consumer by using the URL query parameter ?f ...

Show only upon initial entry: > if( ! localStorage.getItem( "runOnce" ) ) { activate anchor link

My JavaScript form performs calculations, but I only want it to display the first time a visitor enters the site. I attempted to add the following code before my script: jQuery(document).ready(function($) { if( ! localStorage.getItem( "runOnce" ) ) { ...

Guide on retrieving POST data in sveltekit

Hello, I'm new to sveltekit and I am trying to fetch post data in sveltekit using a POST request. Currently, I am utilizing axios to send the post data. const request = await axios .post("/api/user", { username, email, ...